2017-09-23 129 views
0

如何獲得與查詢 SQL我在下面如何將多行轉換爲單行?

表A

ID | Title |Count 
--- |-------- |----- 
1 |Mouse | 50 
2 |pen  | 60 

表B

ID | CompName| 
--- |---------| 
1 |Comp1 | 
2 | Comp2 | 
3 |Comp3 | 

表筆

|---------------------| 
|IDA | IDB | CountT| 
|-------|-----|-------| 
|1  | 1 | 5 |  
|2  | 1 | 6 |  
|1  | 2 | 7 |  
+---------------------+ 

我想要的形式,三個表做出這樣的報告

| object | Copm1 | Comp2 | Comp3 |Sum|remaining | 
|--------|-------|-------|-------|---|--------- | 
| Mouse | 5  | 7  | 0  | 12| 38  | 
| pen | 6  | 0  | 0  | 6 | 54  | 

我的回答我的問題

我可以使用旋轉功能

DECLARE @SQLQuery AS NVARCHAR(MAX) 
DECLARE @PivotColumns AS NVARCHAR(MAX) 
SELECT @PivotColumns= COALESCE(@PivotColumns + ',','') + 
    QUOTENAME(CompName) from B 

set @SQLQuery=N'select pvt.title as object, ' + @PivotColumns + ' 
FROM 
(select title, CountT,CompName 
from T 
    inner join A on T.IDA = A.ID 
    inner join B on B.ID = T.IDA) AS src PIVOT 
    (
max(CountT) 
FOR CompName IN (' + @PivotColumns + ') 
) AS pvt;' 
EXEC sp_executesql @SQLQuery 

回答

2
select a.title as object, 
    sum(case when b.id=1 then T.countT else 0 end) as Comp1, 
    sum(case when b.id=2 then T.countT else 0 end) as Comp2, 
    sum(case when b.id=3 then T.countT else 0 end) as Comp3, 
    sum(t.countt) as 'Sum', 
    max(a.count)-sum(t.countt) as Remaining 
from TableT t 
    inner join tableA A on a.id=t.IDA 
    inner join TableB b on b.id=t.IDB  
    group by a.Title 

http://rextester.com/l/sql_server_online_compiler

得到最終的答案