简体   繁体   中英

Group by clause query with derived fields

My table has quantity, sale price and sale date, and I need to derive the sales price and group the sales by month. I used the below but wasn't able to get the group by clause right.

select 
    (QUANTITY*SALEPRICE) as sales,
    DATEPART (month, saledate) as MM
from [dbo].[PETSALE]
GROUP BY DATEPART (month, saledate)

You would need an aggregate function in the select clause to make your statement a valid aggregate query.

I would phrase your query as:

select 
    sum(quantity * saleprice) as sales,  -- aggregate function
    year(saledate) yyyy,
    month(saledate) mm
from [dbo].[petsale]
group by year(saledate), month(saledate)

Note that I added the sales year to the select and group by clauses: in case your data spreads over more than 12 months, you probably don't want sales from the same month in different years to be grouped together. But if you do, you can just remove year(saledate) from the query.

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