按季度分组

时间:2018-08-15 15:11:32

标签: sql sql-server ssms-2014

如何在SQL中将每周数据分组为季度数据?

我希望下面的代码返回语句中选择的列,但要按季度汇总销售额,而不是返回每周数据。

我的代码:

select
    pz.PriceZoneID,
    pz.Name,
    es.ClientDepartmentID,
    es.DepartmentName,
    es.ClientCategoryID,
    es.CategoryName,
    es.ClientSubCategoryID,
    es.SubCategoryName,
    es.ClientProductID,
    es.ProductName,
    ash.Sales as Units, 
    ash.price * ash.Sales as CashSales, 
    ash.Cost, 
    CAST(ash.date as Date) as Date 
from aggregatedsaleshistory as ash 
join v_EnterpriseStructure as es on es.ProductSID = ash.ProductSID
join PriceZone as pz on pz.PriceZoneID = ash.PriceZoneID 
WHERE es.SubCategoryName = 'Yogurt'
GROUP BY 
    pz.PriceZoneID,
    pz.Name,
    es.ClientDepartmentID,
    es.DepartmentName,
    es.ClientCategoryID,
    es.CategoryName,
    es.ClientSubCategoryID,
    es.SubCategoryName,
    es.ClientProductID,
    es.ProductName,
    ash.Cost,
    ash.Date 

输出的最后一列具有每周日期。所以我的问题是如何将每周数据分为几个季度?我将在此处粘贴一个示例,但不确定如何在此处提供示例数据?保存修改后,我刚刚粘贴的示例就以一种奇怪的格式出现了!

预先感谢?

1 个答案:

答案 0 :(得分:0)

特定的错误消息没有意义,因为您在pz.PriceZoneID中确实有GROUP BY。如果您在GROUP BY前加了分号(我在问题的查询中看不到分号),则会发生这种情况。

但是您仍然有问题。您正在汇总太多列。 group by应该是:

GROUP BY
    pz.PriceZoneID,
    pz.Name,
    es.ClientDepartmentID,
    es.DepartmentName,
    es.ClientCategoryID,
    es.CategoryName,
    es.ClientSubCategoryID,
    es.SubCategoryName,
    ash.SegmentID,
    es.ClientProductID,
    es.ProductName

除了SELECT以外,这些都是ash.cost中所有未汇总的列,可能不应该存在。

相关问题