[英]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.
我使用了以下内容,但无法正确使用 group by 子句。
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.您需要
select
子句中的聚合 function 使您的语句成为有效的聚合查询。
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.请注意,我将销售年份添加到
select
和group by
子句中:如果您的数据分布超过 12 个月,您可能不希望将不同年份同一月份的销售额组合在一起。 But if you do, you can just remove year(saledate)
from the query.但如果你这样做,你可以从查询中删除
year(saledate)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.