Home > Software design >  Returning query in a row wise format instead of column
Returning query in a row wise format instead of column

Time:10-20

Currently I have 2 tables, a listing table and a logs table. With the following query I'm trying to get the listings of a product on a particular day, and it returns the right output.

with X as (
  select 
    l.*,
    (select status_from from logs where logs.refno = l.refno and logs.logtime >= '2021-10-01' order by logs.logtime limit 1) logstat
  from listings l
  where l.added_date < '2021-10-01'
)
, Y as (select X.*, ifnull(X.logstat, X.status) stat from X)
SELECT 
  status.text,
  COUNT(Y.id) AS c 
from status
left join Y on Y.stat = status.code
group by status.code, status.text;

This gives an output like this:

enter image description here

Here I've filtered the query by 1 date which in this case is 2021-10-01. The output should look like:

Publish Action Let Sold Draft
0 3 0 1 1
0 2 0 1 2

Dbfiddle: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=5e0b8d484a41ac9104d0fb002e7f9a3c

CodePudding user response:

You can try below query -

with X as (
  select 
    l.*,
    (select status_from from logs where logs.refno = l.refno and logs.logtime >= '2021-10-02' order by logs.logtime limit 1) logstat
  from listings l
  where l.added_date between '2021-10-01 00:00:00' and '2021-10-02 00:00:00'      -- Start and end date range.
)
, Y as (select X.*, ifnull(X.logstat, X.status) stat20211001 from X)
SELECT 
  added_date,
  COUNT(CASE WHEN status.text = 'Publish' THEN Y.id END) AS Publish,
  COUNT(CASE WHEN status.text = 'Action' THEN Y.id END) AS Action,
  COUNT(CASE WHEN status.text = 'Let' THEN Y.id END) AS Let,
  COUNT(CASE WHEN status.text = 'Sold' THEN Y.id END) AS Sold,
  COUNT(CASE WHEN status.text = 'Draft' THEN Y.id END) AS Draft
from status
join Y on Y.stat20211001 = status.code
group by added_date;

Demo.

  • Related