简体   繁体   中英

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 | 6/2/19 - 9/13/19 Quantity

This answers the original question.

You can use join with a list of dates:

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

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