简体   繁体   中英

SQL Server Query Indicating Amount sold over 3 different time periods

I am trying to write a SQL query that selects from a table some data. The data I want includes how many times an item has sold and the goal is to have columns have that indicate how many times the item has sold in 30,60, and 90 days. I can write 3 separate queries that do the job but I would like to write one query so the data is all on one resulting table. This is what I have so far:

DECLARE @30daysago DATETIME = DATEADD(DAY,-30,CAST(GETDATE() AS DATE));
DECLARE @90daysago DATETIME = DATEADD(DAY,-90,CAST(GETDATE() AS DATE));

Set NOCOUNT ON
Select company_info_1 from setup

select ii.itemnum, i.itemname,i.price, d.description, count(ii.itemnum)
from invoice_itemized ii
join invoice_totals IT on it.invoice_number=ii.invoice_number
join inventory i on i.itemnum=ii.itemnum
join departments d on d.dept_id=i.dept_id
where it.datetime > @30daysago and len(ii.itemnum) >4
group by ii.itemnum, i.itemname, d.description, i.price
order by count(ii.itemnum) desc

Use a single query with conditional aggregation:

SELECT
    ii.itemnum,
    i.itemname,
    i.price,
    d.description,
    COUNT(ii.itemnum) AS total,
    COUNT(CASE WHEN it.datetime > DATEADD(DAY, -30, CAST(GETDATE() AS DATE))
               THEN ii.itemnum END) AS 30daysago,
    COUNT(CASE WHEN it.datetime > DATEADD(DAY, -90, CAST(GETDATE() AS DATE))
               THEN ii.itemnum END) AS 90daysago
FROM invoice_itemized ii
INNER JOIN invoice_totals IT
    ON it.invoice_number = ii.invoice_number
INNER JOIN inventory I
    ON i.itemnum = ii.itemnum
INNER JOIN departments d
    ON d.dept_id = i.dept_id
WHERE
    LEN(ii.itemnum) > 4
GROUP BY
    ii.itemnum,
    i.itemname,
    d.description,
    i.price
ORDER BY
    ii.itemnum DESC;

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