简体   繁体   中英

Transpose date columns into rows (PostgreSQL)

I have a table look like this:

    ID    brand    version   stock   date

    1     AA         AAA      50     2019-11-11
    1     AA         AAA      52     2019-11-12
    1     AA         AAA      49     2019-11-13
    ...

    2     BB         BBB      30     2019-11-11
    2     BB         BBB      31     2019-11-12 
    2     BB         BBB      31     2019-11-13
   ...

basically the date column is dynamic, because I extracted the last 14 days from now by using:

  select id, brand, version, stock, date, DATEADD(DAY, -8, getdate()) as date_add
  from myTable 
  where date > date_add

meaning that a week after the dates will be different than now, so my problem is how can I transpose this dynamic table? as I only know the trick to use "case..when", but in this case it doesn't work.

My desired output will be:

ID    brand    version   2019-11-11  2019-11-12  2019-11-13

1     AA         AAA         50         52          49           ...    
2     BB         BBB         30         31          31           ...

I have searched the similar question, but there is only answer for using SQL Server for dynamic way of transpose.

How can I approach this? Thanks!

You can use the code below:

SET @sql = NULL;
SELECT
    GROUP_CONCAT(DISTINCT
    CONCAT(
      'SUM(CASE WHEN action = "',
      action,'"  AND ', 
           (CASE WHEN pagecount IS NOT NULL 
           THEN CONCAT("pagecount = ",pagecount) 
           ELSE pagecount IS NULL END),
      ' THEN 1 ELSE 0 end) AS ',
      action, IFNULL(pagecount,'')

    )
  )
INTO @sql
FROM
  t;

SET @sql = CONCAT('SELECT company_name, ', @sql, ' 
                  FROM t 
                   GROUP BY company_name');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

It comes from that same link and doesn't use the in command. It build a dynamic string containg the data from the pivoted columns

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM