如何汇总来自同一表的不同项目组的前1条记录?

时间:2019-07-07 10:20:49

标签: sql sql-server

我想对不同组的top1结果的总和。

Select PCCI.BWPrintQty 
from PrintCusClickRecord PCCI 
where Convert(Date, pcci.ClickMonth) < Convert(Date, '2019-01-01') 
  and PCCI.OrderID != 129012 and ISNULL(PCCI.IsDelete, 0) != 1 
  and PCCI.ItemTrackingNo in ('C397P800803', 'G145P901553', 'G146P300748') 
order by PCCI.ClickMonth desc

以下是

的数据
Click record for C397P800803        
-------------------------------
300,
200,
100

Click record for G145P901553
-------------------------------
400,
250,
150

Click record for G146P300748
-------------------------------
500,
450,
350

输出应为上述同一表中所有第一条记录的总和。 意思是= 300 + 400 + 500 = 1200(结果)

3 个答案:

答案 0 :(得分:0)

我建议将ItemTrackingNo按其最大值BWPrintQty分组(我假设这是示例中数字的列,应用您在问题中提到的过滤器,并对结果进行汇总

(select sum(first) from 
  (select 
    max(BWPrintQty) as first, 
    ItemTrackingNo
  from PrintCusClickRecord 
  where 
  Convert(Date,pcci.ClickMonth) < Convert(Date,'2019-01-01') 
  and PCCI.OrderID!= 129012 
  and ISNULL(PCCI.IsDelete,0)!=1 
  and PCCI.ItemTrackingNo in('C397P800803', 'G145P901553' ,'G146P300748') 
  group by ItemTrackingNo)
)

答案 1 :(得分:0)

您可以使用Rank函数。

SELECT SUM(PrintQty) FROM (
Select PCCI.BWPrintQty AS PrintQty, RANK() OVER (
    PARTITION BY PCCI.ItemTrackingNo
    ORDER BY PCCI.ClickMonth desc
) as [Rank]
from PrintCusClickRecord PCCI 
where  Convert(Date,pcci.ClickMonth) < Convert(Date,'2019-01-01') 
and PCCI.OrderID!= 129012 and ISNULL(PCCI.IsDelete,0)!=1 
and PCCI.ItemTrackingNo in('C397P800803'
                           'G145P901553'
                           ,'G146P300748'
                           ) 
) S
WHERE S.[Rank] = 1

查询产生的值例如:

Click record for C397P800803        
-------------------------------
300, 1
200, 2
100, 3

Click record for G145P901553
-------------------------------
400, 1
250, 2
150, 3

Click record for G146P300748
-------------------------------
500, 1
450, 2
350, 3

然后将其过滤为等级等于1 => 300, 400, 500的记录,并计算它们的总和。

答案 2 :(得分:0)

Row_number根据需要并采用第一个。

select sum(BWPrintQty) 
from (
    select PCCI.BWPrintQty 
       -- order by PCCI.ClickMonth if you need first month
      , row_number() over(partition by PCCI.ItemTrackingNo order by PCCI.BWPrintQty desc) pos 
    from PrintCusClickRecord PCCI 
    where  Convert(Date,pcci.ClickMonth) < Convert(Date,'2019-01-01') 
       and PCCI.OrderID!= 129012 and ISNULL(PCCI.IsDelete,0)!=1 
       and PCCI.ItemTrackingNo in('C397P800803'
                                ,'G145P901553'
                                ,'G146P300748'
                               ) 
   ) t
where pos = 1;