2015-01-08 2 views
0

다음 SQL 문이 있습니다. 나는에게데이터를 롤업 할 SQL Server 쿼리

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 

불행하게도 :

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 

내 목표 결과는 다음 표를 얻을 수 있습니다 : 결과는 다음과 같다 Person, DeliverableDeliverableActions

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 

의 세 가지 테이블을 조인 내가하는 일을 설명하기 위해 어떤 용어를 모르겠다. '그룹화'와 '집계'를 검색했지만 응답이 없으므로 커뮤니티에 추가합니다. 당신의 도움에 미리 감사드립니다.

당신이 case based aggregation를 사용하거나 당신은 또한 사용할 수 있습니다

답변

1

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

에 'case ** when ** da.type ...'이 추가되었으며 –

+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
설명 된대로 SQL 서버 2008+를 사용하는 경우 당신은 PIVOT

을 찾고

, 그것은 피벗 기능이 있습니다 at 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;