如果满足第一个group by子句,如何组合行

时间:2017-03-16 21:22:46

标签: sql sql-server sql-server-2008

我有一个简单的查询,可以为员工提取每个位置的设置。

我们说我有以下数据:

Username   Store_number   Invoice_amt
TJ1          1                5
TJ1          1                5
TJ1          2                5
RB2          3                5
RB2          3                5
DD1          4                5
DD1          4                5

我有一个问题:

Select username, Sum(invoice_amt) as Total, Store_number

我将输出以下内容:

username    Total      store_number
TJ1          10          1
TJ1          5           2
RB2          10          3
DD1          10          4

我想要做的事情 - 首先将用户名组合起来,然后按商店编号将其拆分 - 我的输出是否有办法:

username    Total      store_number
TJ1          15          1
RB2          10          3
DD1          10          4

3 个答案:

答案 0 :(得分:1)

您可以选择min(store_number)

select 
    username
  , Sum(invoice_amt) as Total
  , min(store_number) as Store_number
from t
group by username

答案 1 :(得分:1)

我意识到你可能不想要最小的商店。您可能想要商店最常见的价值。如果是这样的话:

select username, amount,
       max(case when seqnum = 1 then store end) as most_common_store
from (select username, store, sum(invoice_amount) as amount,
             row_number() over (partition by username order by sum(invoice_amount) desc) as seqnum
      from t
      group by username, store
     ) us
group by username;

答案 2 :(得分:0)

如果我理解你的问题,这将是你的查询。

Select 
username,
sum(invoice_amt) as Total,
Min(store_number) as store_number
from Table!
Group By UserName