2015-01-08 138 views
0

我有以下SQL語句。它連接三個表:PersonDeliverableDeliverableActionsSQL Server查詢彙總數據

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 

不幸的是我不知道用什麼術語來描述我在做什麼。我搜索了「分組」和「聚合」,但我沒有答案,所以我把它放到了社區中。預先感謝您的幫助。

回答

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 
+0

我得到'不正確的語法附近「=」。「 –

+0

在** da.type ...時添加了'case **',它的工作原理是 –

+0

@ user1571934,您是對的.. – radar

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 
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;