SQL Server查询以汇总数据

时间:2015-01-08 18:58:49

标签: sql sql-server

我有以下SQL语句。它加入了三个表:PersonDeliverableDeliverableActions

select 
    p.first_name, p. last_name, d.title, da.type 
from 
    Deliverable d
right join 
    Person p on d.person_responsible_id = p.id
right join 
    DeliverableAction da on da.DeliverableID = d.id
where 
    d.date_deadline >= @startDate and
    d.date_deadline <= @endDate
order by 
    d.title

结果如下:

first_name | last_name   | title        | type
-----------+-------------+--------------+------
Joe        | Kewl        | My_Report_1  | 2
Joe        | Kewl        | My_Report_1  | 3
Joe        | Kewl        | My_Report_1  | 1
Sly        | Foxx        | Other_Rep_1  | 1
Sly        | Foxx        | Other_Rep_1  | 2

我的目标是得到下表:

first_name | last_name  | title        | type_1 | type_2 | type_3 | type_4
-----------+------------+--------------+--------+--------+--------+---------
Joe        | Kewl       | My_report_1  | 1      | 1      | 1      | 0
Sly        | Foxx       | Other_Rep_1  | 1      | 1      | 0      | 0

不幸的是,我不知道用什么术语来描述我在做什么。我搜索过“分组”和“聚合”,但我没有回答,所以我把它放到了社区。提前感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

您可以使用case based aggregation,也可以使用pivot

select p.first_name, 
       p. last_name, 
       d.title, 
       sum(case when da.type = 1 then 1 else 0 end) as type_1,
       sum(case when da.type = 2 then 1 else 0 end) as type_2,
       sum(case when da.type = 3 then 1 else 0 end) as type_3,
       sum(case when da.type = 4 then 1 else 0 end) as type_4,
    from Deliverable d
    right join Person p on d.person_responsible_id = p.id
    right join DeliverableAction da on da.DeliverableID = d.id
    where d.date_deadline >= @startDate and
          d.date_deadline <= @endDate
    group by p.first_name, p.last_name, d.title

答案 1 :(得分:0)

select
first_name, last_name, title,
sum(case when type = 1 then 1 else 0 end) as type_1
from 
(
select p.first_name, p. last_name, d.title, da.type from Deliverable d
right join Person p on d.person_responsible_id = p.id
right join DeliverableAction da on da.DeliverableID = d.id
where d.date_deadline >= @startDate and
      d.date_deadline <= @endDate
 ) as a
 group by first_name, last_name, title

答案 2 :(得分:0)

你正在寻找PIVOT

如果您使用的是SQL Server 2008+,则它具有http://technet.microsoft.com/en-us/library/ms177410%28v=sql.105%29.aspx

中所述的数据透视功能

基本上,你写的东西(对不起,我只是从引用的链接粘贴了例子,但这应该给你一些想法):

-- Pivot table with one row and five columns
SELECT 'AverageCost' AS Cost_Sorted_By_Production_Days, 
[0], [1], [2], [3], [4]
FROM
(SELECT DaysToManufacture, StandardCost 
    FROM Production.Product) AS SourceTable
PIVOT
(
AVG(StandardCost)
FOR DaysToManufacture IN ([0], [1], [2], [3], [4])
) AS PivotTable;