SQL选择分组结果

时间:2015-04-13 17:12:20

标签: sql sql-server

我需要按以下格式创建报告(第一行的分隔符包含列标题,所有帐户的总数是给定AE的Account.Value的总和,以及帐户名称和值通过帐户名称升序按AE每个AE分组,按AE名字升序排序):

AE             |    Account Value                      | # of Calls
Amy Adams           $5000 (total for all accounts) 
  *Acme Inc.        $1000                                5
  *Noon Inc.        $3000                                7  
  *Tazo Inc.        $1000                                2
Ben Smith           $7000 (total for all accounts) 
  *Airo Inc.        $2000                                9
  *Fifa Inc.        $5000                                8  
Dan Morse           $2000 (total for all accounts) 
  *Yakk Inc.        $1000                                1
  *Zero Inc.        $1000                                2  

来自下表:

Table [AE]
Column [AeId] int
Column [FirstName] varchar
Column [LastName] varchar

Table [Account]
Column [AccountId] int
Column [Name] varchar
Column [Value] decimal
Column [AeId] int (foreign key AE.AeId)

Table [Call]
Column [CallId] int
Column [DateCreated] datetime
Column [AccountId] int (foreign key Account.AccountId)

任何帮助都会受到赞赏,因为我不确定如何以这种方式对数据进行分组。 谢谢你的任何建议。

1 个答案:

答案 0 :(得分:0)

您可以尝试使用WITH ROLLUP或WITH CUBE ......

但我会像这样使用CTE:

create Table [AE] (
[AeId] int,
[FirstName] varchar(50),
[LastName] varchar(50)
)
create Table [Account] (
[AccountId] int,
[Name] varchar(50),
[Value] decimal,
[AeId] int
)
create Table [Call] (
[CallId] int,
[DateCreated] datetime,
[AccountId] int
)
insert into ae values (1, 'Brett', 'Green')
insert into ae values (2, 'John', 'Doe')
insert into account values (1, 'Account 1', 10000, 1)
insert into account values (2, 'Account 2', 5000, 1)
insert into account values (3, 'Account 3', 3000, 1)
insert into account values (4, 'Account 4', 1000, 2)
insert into account values (5, 'Account 5', 5000, 2)
insert into account values (6, 'Account 6', 3000, 2)

insert into call values (1, current_timestamp, 1)
insert into call values (2, current_timestamp, 1)
insert into call values (3, current_timestamp, 2)
insert into call values (4, current_timestamp, 3)
insert into call values (5, current_timestamp, 4)
insert into call values (6, current_timestamp, 5)
insert into call values (7, current_timestamp, 5)

;WITH data as (
SELECT 
    ae.FirstName + ' ' + ae.LastName AS Name,
    a.Name AS AccountName,
    SUM(a.Value) AS AccountValue,
    COUNT(DISTINCT c.CallId) AS NumberOfCalls
FROM AE ae
INNER JOIN Account a
    ON a.AeId = ae.AeId
INNER JOIN Call c
    ON c.AccountId = a.AccountId
GROUP BY
    ae.FirstName + ' ' + ae.LastName,
    a.Name
)
select Name, '' AS AccountName, SUM(AccountValue) AS AccountValue, SUM(NumberOfCalls) AS NumberOfCalls
from data
group by Name
union all
select Name, AccountName, AccountValue, NumberOfCalls
from data
order By name