Get data for a given number of days by converting rows to column dynamically

时光毁灭记忆、已成空白 提交于 2019-12-13 05:23:51

问题


This is a follow-up to my previous question: Get records for last 10 dates

I have to generate reports for all books of a store along with sold count (if any) for the last N dates, by passing storeId.

   BOOK               Book Sold                   Store
 ------------        --------------------        ---------------- 
 Id  Name  SID     Id Bid Count Date            SID  Name
  1   ABC   1      1   1   20  11/12/2015        1    MNA
  2   DEF   1      2   1   30  12/12/2015        2    KLK
  3   DF2   2      3   2   20  11/12/2015        3    KJH
  4   DF3   3      4   3   10  13/12/2015
  5   GHB   3      5   4    5  14/12/2015

The number of days N is supplied by the user. This is the expected output for the last 4 dates for storeId -1,2 & 3.

 BookName  11/12/2015 12/12/2015  13/12/2015  14/12/2015
  ABC         20        30         --             --    
  DEF         20        --         --             -- 
  DF2         --        --         10             -- 
  DF3         --        --         --              5
  GHB         --        --         --             --

If the user passes 5 than data for the last 5 days shall be generated, starting date as 14/12/2015.

I am using Postgres 9.3.


回答1:


Cross table without crosstab function:

SELECT
SUM(CASE book.Date ='11/11/2015' THEN book.Count ELSE 0 END) AS '11/11/2015',
SUM(CASE book.Date ='15/11/2015' THEN book.Count ELSE 0 END) AS '15/11/2015',
SUM(CASE book.Date ='17/11/2015' THEN book.Count ELSE 0 END) AS '17/11/2015'
FROM
store,
book
WHERE
store.Id = booksold.Bid
AND store.Id IN (1,2)
GROUP BY
book.Name
ORDER BY
book.id ASC;


来源:https://stackoverflow.com/questions/32933910/get-data-for-a-given-number-of-days-by-converting-rows-to-column-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!