简体   繁体   English

SQL 查询以在每个月的第一天到最后一天的列中显示每日计数结果

[英]SQL Query to Display Daily Count Results in Columns from 1st to last day of month

Need a Query to Display daily count of each item bought by customers in columns from 1st day of month to last day需要一个查询来显示从每月的第一天到最后一天的列中客户购买的每件商品的每日计数

Sample data table "Item"示例数据表“项目”

+--------+--------+----------+---------------+
| Purchase Date | Item Code| Item Name| Price|
|--------+--------+----------+--------------+
| 01-JAN-20     | 11       | Apple   | 1    |
| 01-JAN-20     | 11       | Apple   | 1    |
| 02-JAN-20     | 12       | Orange  | 2    |
| 02-JAN-20     | 11       | Apple   | 1    |
| 03-JAN-20     | 12       | Orange  | 2    |
| 03-JAN-20     | 12       | Orange  | 2    |
| 04-JAN-20     | 12       | Orange  | 2    |
| 04-JAN-20     | 11       | Apple   | 1    |
+--------+--------+----------+--------------+

SQL Query should Display Daily Count using Item code and Result to be displayed as below table. SQL 查询应使用项目代码显示每日计数,结果如下表所示。 Count daily with each day displayed in column base on the day eg If today is 4th of Jan then count tomorrow will create new column with count result and continues until last day of month or something similar.每天计数,每一天都显示在当天的列中,例如如果今天是 1 月 4 日,那么明天计数将创建具有计数结果的新列,并持续到月的最后一天或类似的东西。

+--------+--------+----------+---------------+
| Items  | Jan 01| Jan 02| Jan 03|Jan 04| etc
+--------+--------+----------+--------------+
| Apple  | 2     |   1   |   2   |   1  |
| Orange | 0     |   1   |   0   |   1  |
+--------+--------+----------+--------------+

If you know what dates you want, you can use conditional aggregation:如果你知道你想要什么日期,你可以使用条件聚合:

select item,
       sum(case when purchase_date = '2020-01-01' then 1 else 0 end) as jan_1,
       sum(case when purchase_date = '2020-01-02' then 1 else 0 end) as jan_2,
       sum(case when purchase_date = '2020-01-03' then 1 else 0 end) as jan_3,
       sum(case when purchase_date = '2020-01-04' then 1 else 0 end) as jan_4,
       . . .
from items
group by item;

Note that this assumes that purchase_date is really stored as an internal date format.请注意,这假设purchase_date确实存储为内部日期格式。 So the comparison is a date constant -- however, that might differ among databases.所以比较是一个日期常数——但是,这可能因数据库而异。

If you do not have a specific set of dates in mind, then you will need to use dynamic SQL.如果您没有特定的日期集,则需要使用动态 SQL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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