SQL中基于总和的最高价值维度

问题描述

我在查询每个位置的顶级交易类型时遇到问题:

我的表的位置为varchar,类型为varchar,事务为int

我尝试了以下操作并收到错误消息:

select  
c.location,c.type,sum(c.transaction) as trans_sum
from sales c
group by c.location,c.type
having trans_sum = (
select top 1
c2.type,sum(c2.transaction) as trans_sum2
from sales c2
where c2.location = c.location
group by c2.location,c2.type
order by c2.location,trans_sum2 desc
)
order by c.location,trans_sum desc;

基本上,我想要每种类型和位置的交易列的最高汇总值。

Location Type    Noun
--------------------- 
Atlanta  Channel 750 
Atlanta  Direct  2250 
Atlanta  CC      1850 
Chicago  Channel 625 
Chicago  Direct  1125 
Chicago  CC      612
Dallas   Channel 2183
Dallas   Direct  1165
Dallas   CC      965

...................................... 我正在寻找的结果是: ................................

    Location Type    Noun
    ---------------------  
    Atlanta  Direct  2250 
    Chicago  Direct  1125
    Dallas   Channel 2183

...................................

因此,返回的sql列表的顶部位置并键入汇总值。我还要每个位置/类型配对的前3个值

解决方法

删除您选择的c2.type

select  
c.location,c.type,sum(c.transaction) as trans_sum
from sales c
group by c.location,c.type
having trans_sum = (
select top 1
sum(c2.transaction) as trans_sum2
from sales c2
where c2.location = c.location
group by c2.location,c2.type
order by c2.location,trans_sum2 desc
)
order by c.location,trans_sum desc;
,

您可能使用sql-server !?如果是这样,我在使用名称“ transaction”作为列时遇到了第一个错误。该名称已被sql server使用,因此我对其进行了更改。

第二,我认为您不能在Have语句中使用别名“ trans_sum”。改为使用sum(c.trans)。

这应该有效:

select  
       c.location,sum(c.trans) as trans_sum
 from  foobar c
group by c.location,c.type
having sum(c.trans) = (
         select top 1
                sum(c2.trans) as trans_sum2
           from foobar c2
          where c2.location = c.location
          group by c2.location,c2.type
          order by c2.location,trans_sum2 desc
        )
order by c.location,trans_sum desc;