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