Sql 分组时重复的结果

Sql 分组时重复的结果,sql,sql-server,Sql,Sql Server,我需要写一些代码,按区域按周分组销售见附件第一张图片 我写了下面的代码,但是,它返回了重复的结果,例如“Misc冷藏食品”类别在12月17日和24日出现了两次,见附件第二个屏幕截图。 有人知道吗 1我如何修改代码,使该类别在每个日期仅出现一次,以及 2如何修改代码,以便在从所选字段中删除类别时,价格区ID和名称在每个日期仅显示一次 蒂亚 一种选择是简单地选择具有最大单位数的行 select p.PriceZoneID, p.Name, max(p.Units) as Units, p.Date

我需要写一些代码,按区域按周分组销售见附件第一张图片

我写了下面的代码,但是,它返回了重复的结果,例如“Misc冷藏食品”类别在12月17日和24日出现了两次,见附件第二个屏幕截图。

有人知道吗

1我如何修改代码,使该类别在每个日期仅出现一次,以及 2如何修改代码,以便在从所选字段中删除类别时,价格区ID和名称在每个日期仅显示一次

蒂亚


一种选择是简单地选择具有最大单位数的行

select p.PriceZoneID, p.Name, max(p.Units) as Units, p.Date, p.CategoryName 
from
(
    Select 
        ps.PriceZoneID,
        ps.Name,
        sum (ash.Sales) as Units, 
        ash.date,  
        es.CategoryName 
    FROM AggregatedSalesHistory as ash  
    JOIN v_EnterpriseStructure as es ON es.ProductSID = ash.ProductSID
    JOIN PriceZone as ps ON ps.PriceZoneID = ash.PriceZoneID

    WHERE DepartmentName ='Dairy'
        and ash.Date >= '12-17-2014' and ash.date<= '12-31-2014' 
    GROUP BY
        ps.PriceZoneID,
        ps.Name,
        es.CategoryName,
        ash.Sales, 
        ash.Date
) p
group by p.PriceZoneID, p.Name, p.Date, p.CategoryName 
--If category isn't there remove the field and the group by category

通过删除组中的ash.sales。将要聚合的列放入组中会使聚合毫无意义。例如,值289的和是289;因为这是唯一的价值啊,酷!谢谢拉努!将ash.sales从组中移除使其工作!但是,如果我通过从组中删除了es.CategoryName,则会出现一个错误,即列“v_EnterpriseStructure.CategoryName”在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。您知道如何按从组中删除类别名称,但仍按区域和日期返回聚合结果吗?另一方面,对于进一步的问题,请确保不要将数据作为图像发布,尤其是不要将代码发布;其他用户无法与其交互,很可能是因为您的问题被否决。是否从您的选择中删除es.CategoryName?这个错误实际上就是告诉你这里的错误。哦,好的。谢谢你让我知道!我最初是从Excel中复制文本的,但粘贴到这里时格式不好,因此我附加了一个图像,以使人们尽可能容易地看到我在做什么。
select p.PriceZoneID, p.Name, max(p.Units) as Units, p.Date, p.CategoryName 
from
(
    Select 
        ps.PriceZoneID,
        ps.Name,
        sum (ash.Sales) as Units, 
        ash.date,  
        es.CategoryName 
    FROM AggregatedSalesHistory as ash  
    JOIN v_EnterpriseStructure as es ON es.ProductSID = ash.ProductSID
    JOIN PriceZone as ps ON ps.PriceZoneID = ash.PriceZoneID

    WHERE DepartmentName ='Dairy'
        and ash.Date >= '12-17-2014' and ash.date<= '12-31-2014' 
    GROUP BY
        ps.PriceZoneID,
        ps.Name,
        es.CategoryName,
        ash.Sales, 
        ash.Date
) p
group by p.PriceZoneID, p.Name, p.Date, p.CategoryName 
--If category isn't there remove the field and the group by category