简体   繁体   English

SQL 服务器创建基于不同日期范围合计数量的查询

[英]SQL Server Creating query that totals quantities based on different date ranges

I'm trying to run a query that breaks down quantity sold during different time periods into different columns while grouping by the item sold.我正在尝试运行一个查询,将不同时间段内的销售数量分解为不同的列,同时按销售的项目进行分组。

For now I use现在我使用

SELECT t.category, t.item, i.descrip, sum(t.quantity)
FROM transact t
JOIN items i on t.department=i.department and t.category=i.category and t.item=i.item
WHERE t.department = '2070'
and t.date_time between '2019-03-18' and '2019-06-01'
GROUP BY t.category, t.item, i.descrip
ORDER BY t.category, t.item, i.descrip

and just change the date range after each run.并在每次运行后更改日期范围。 I'd rather have one query that I can have the different date ranges split into different columns.我宁愿有一个查询,我可以将不同的日期范围分成不同的列。

My columns would end up being: Category |我的专栏最终会是:类别 | Item |项目 | Descrip |描述 | 3/18/19 - 6/1/19 Quantity | 3/18/19 - 6/1/19 数量 | 6/2/19 - 9/13/19 Quantity 6/2/19 - 9/13/19 数量

This answers the original question.这回答了最初的问题。

You can use join with a list of dates:您可以将join与日期列表一起使用:

SELECT v.start_dt, v.end_dt, t.category, t.item, i.descrip, 
       SUM(t.quantity)
FROM transact t JOIN
     items i 
     ON t.department = i.department AND
        t.category = i.category 
        AND t.item = i.item JOIN
     (VALUES (CONVERT(DATE, '2019-03-18'), CONVERT(DATE, '2019-06-01'),
             (CONVERT(DATE, '2018-03-18'), CONVERT(DATE, '2018-06-01')
     ) v(start_dt, end_dt)
     ON t.date_time BETWEEN v.start_dt AND v.end_dt
WHERE t.department = '2070'
GROUP BY  v.start_dt, v.end_dt, t.category, t.item, i.descrip
ORDER BY v.start_dt, v.end_dt, t.category, t.item, i.descrip

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

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