如何使用Query获取sql 我在下面的表格中有三个表格
表A
ID | Title |Count
--- |-------- |-----
1 |Mouse | 50
2 |pen | 60
表B
ID | CompName|
--- |---------|
1 |Comp1 |
2 | Comp2 |
3 |Comp3 |
表T
|---------------------|
|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 |
我对我的问题的回答
我能够使用PIVOT功能获得最终答案
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
答案 0 :(得分: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