我有这张桌子:
persnid | elemntref | val
100 | 1 | 5000
100 | 2 | 2500
100 | 3 | 3100
我想使用以下条件:
IF elemntref = 1 THEN create new column that name is 'pay'
IF elemntref = 2 THEN create new column that name is 'pay2'
IF elemntref = 3 THEN create new column that name is 'pay3'
运行查询后的表:
persnid | Pay | Pay2 | pay3
100 | 5000 | 2500 | 3100
答案 0 :(得分:2)
你想要一个CASE
SELECT persnid
,SUM(CASE WHEN elemntref = 1 THEN ISNULL(val,0) END) AS pay
,SUM(CASE WHEN elemntref = 2 THEN ISNULL(val,0) END) AS pay2
,SUM(CASE WHEN elemntref = 3 THEN ISNULL(val,0) END) AS pay3
FROM YOUR_TABLE
GROUP BY persnid
答案 1 :(得分:1)
如果elemntref
列值固定为1,2,3,则正常枢轴工作
<强>架构:强>
SELECT * INTO #TAB1 FROM (
SELECT 100 PERSNID, 1 ELEMNTREF, 5000 VAL
UNION ALL
SELECT 100, 2 , 2500
UNION ALL
SELECT 100, 3, 3100
)A
现在以1,2,3作为列进行旋转
SELECT PERSNID, [1] AS PAY, [2] AS PAY2, [3] AS PAY3 FROM (
SELECT * FROM #TAB1
)A
PIVOT
(
SUM(VAL) FOR ELEMNTREF IN ([1],[2],[3])
)PVT
结果将是
+---------+------+------+------+
| PERSNID | PAY | PAY2 | PAY3 |
+---------+------+------+------+
| 100 | 5000 | 2500 | 3100 |
+---------+------+------+------+
答案 2 :(得分:0)
如果行数未知,您也可以使用动态SQL查询执行此操作。
<强>查询强>
declare @sql as varchar(max);
select @sql = 'select [persnid], '
+ stuff((select distinct ', coalesce(sum(case [elemntref] when ' +
cast([elemntref] as varchar(50)) +
' then [val] end), 0) as [pay' + cast([elemntref] as varchar(10)) + ']'
from [your_table_name]
for xml path('')
), 1, 2, '')
+' from [your_table_name] group by [persnid]';
exec(@sql);