SQL按ID /季度分组

时间:2019-02-15 14:38:38

标签: sql

我正在尝试按月份查找产品的整体销售情况(由ProductKey标识)

我发现某些情况下,它将给定月份的某些“产品关键字”归为一组

select distinct pkm.productkey, dateparts.month,year,dateparts.SalesAmount
from dateparts
inner join(
select distinct productkey, month, "salesamount"=sum(salesamount)
from dateparts
group by productkey,Month 
) pkm on pkm.ProductKey = dateparts.ProductKey 
and pkm.salesamount=dateparts.salesamount
order by pkm.productkey, dateparts.month,year  

Expected

PK      MM      YY              SALESAM
266     9       2011        183.9382
266     10      2011        183.9382
267     1       2012        1011.66


Actual

PK      MM      YY              SALESAM
266     9       2011        183.9382
266     10      2011        183.9382
267     1       2012        202.332
267     1       2012        809.328 

3 个答案:

答案 0 :(得分:4)

为什么不简单地在没有inner join的情况下进行汇总?

select productkey, month, year, sum(SalesAmount)
from dateparts d 
group by productkey, month, year;

您的问题可能与ON子句有关,应该将其与ProductKeymonthyear映射。但是,对于您想要的结果,这实际上不是必需的。

答案 1 :(得分:2)

除了分组之外,您似乎还希望针对相同的SUMproductkeymonthyear进行数据

尝试以下代码:

select productkey, month, year, SUM(SalesAmount)
  from dateparts
 group by productkey, month,year
 order by productkey, month,year  

希望我能帮上忙!

答案 2 :(得分:0)

问题就随您加入。

您可以尝试以下吗?

select distinct pkm.productkey, dateparts.month,year,dateparts.SalesAmount
from dateparts
inner join(
select distinct productkey, month, sum(salesamount) as salesAmount1
from dateparts
group by productkey,Month 
) pkm on pkm.ProductKey = dateparts.ProductKey 
and pkm.salesamount1=dateparts.salesamount
order by pkm.productkey, dateparts.month,year