我正在寻找一种在SQL Server中将行转换为列的方法,我尝试了透视,但仍然没有得到想要的结果。
样品表
----------------------------------------
| Code | Value | Status | Desc |
----------------------------------------
| 000010 | 2 | Trx1 | X001 |
| 000010 | 1 | Trx2 | X001 |
| 000010 | 2 | Trx1 | X002 |
| 000010 | 2 | Trx2 | X002 |
| 000010 | 1 | Trx1 | X003 |
| 000010 | 1 | Trx2 | X003 |
从那张桌子,我想得到类似的结果
----------------------------------------
| Code | Status1 | Status2 | Desc |
----------------------------------------
| 000010 | 2 | 1 | X001 |
| 000010 | 2 | 2 | X002 |
| 000010 | 1 | 1 | X003 |
我如何建立这样的结果?
我自己已经想要的结果,谢谢
谢谢
答案 0 :(得分:1)
CREATE TABLE #Table1
([Code] int, [Value] int, [Status] varchar(4), [Desc] varchar(4))
;
INSERT INTO #Table1
([Code], [Value], [Status], [Desc])
VALUES
(000010, 2, 'Trx1', 'X001'),
(000010, 1, 'Trx2', 'X001'),
(000010, 2, 'Trx1', 'X002'),
(000010, 2, 'Trx2', 'X002'),
(000010, 1, 'Trx1', 'X003'),
(000010, 1, 'Trx2', 'X003')
;
SELECT FORMAT([Code],'000000')[Code] ,MAX(CASE WHEN [STATUS]='Trx1' THEN [Value] END) AS [Value1] ,
MAX(CASE WHEN [STATUS]='Trx2' THEN [Value] END) AS [Value2],[Desc]
FROM #Table1
GROUP BY [Code],[Desc]
输出
Code Value1 Value2 Desc
10 2 1 X001
10 2 2 X002
10 1 1 X003
答案 1 :(得分:0)
以防万一,您实际上要为此使用PIVOT。
这是一个代码段:
-- Using a table variable just for demonstration purposes
declare @Table table (Code varchar(6), Value int, [Status] varchar(30), [Desc] varchar(4));
-- Sample data
insert into @Table (Code, Value, [Status], [Desc]) values
('000010', 2, 'Trx1', 'X001')
,('000010', 1, 'Trx2', 'X001')
,('000010', 2, 'Trx1', 'X002')
,('000010', 2, 'Trx2', 'X002')
,('000010', 1, 'Trx1', 'X003')
,('000010', 1, 'Trx2', 'X003')
;
-- The pivot query
select Code, Status1, Status2, [Desc]
from
(
select Code, [Desc], Value,
concat('Status', row_number() over (partition by Code, [Desc] order by [Status])) as Col
from @Table
) as src
pivot
(
max([Value])
for Col in ([Status1], [Status2])
) as pvt
order by Code, [Desc];
基本上,row_number用于生成要旋转的列名。