我打算使用pivot
SRNO DATE TYPE USERNAME
--------------------------------------------
1 16/07/2016 OPENING JOHN
2 13/07/2016 SALES JOHN
3 12/07/2016 OPENING JOHN
4 11/07/2016 PURCHASE ADWARD
5 16/07/2016 OPENING JOHN
6 13/07/2016 SALES JOHN
7 12/07/2016 SALES JOHN
8 12/07/2016 OPENING JOHN
9 19/07/2016 OPENING JOHN
10 12/07/2016 PURCHASE ADWARD
我想要以下格式的上表数据
OPENING_SRNO OPENING_DATE OPENING_USERNAME SALES_SRNO SALES_DATE SALES_USERNAME PURCHASE_SRNO PURCHASE_DATE PURCHASE_USERNAME
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1 16/07/2016 JOHN 2 13/07/2016 JOHN 4 11/07/2016 ADWARD
3 12/07/2016 JOHN 6 13/07/2016 JOHN 10 12/07/2016 ADWARD
5 16/07/2016 JOHN 7 12/07/2016 JOHN
8 12/07/2016 JOHN
9 19/07/2016 JOHN
TYPE
列具有动态值,我发现在pivot in
集合中应用动态列时遇到了困难。
更新
我尝试过关注,但NULL
列中的一些TYPE
值给了我错误。
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX),
@COLS1 AS NVARCHAR(MAX)
SELECT @COLS = STUFF((SELECT DISTINCT ','+QUOTENAME(case when TYPE IS NULL then 'empty' else TYPE end)
FROM TEMP
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
PRINT(@COLS)
set @query = 'SELECT ' + @cols + ' from
(
select SRNO,DATE, USERNAME
from TEMP
) x
pivot
(
MAX(SRNO)
for TYPE in (' + @cols + ')
) p '
PRINT @QUERY
execute(@query);
答案 0 :(得分:0)
不确定,此问题适用于PIVOT
...
不过,这应该可以让你开始:
SELECT
opening_srno, opening_date, opening_username, sales_srno, sales_date,
sales_username, purchase_srno, purchase_date, purchase_username
FROM
(SELECT
srno OPENING_SRNO
, d_date OPENING_DATE
, username OPENING_USERNAME
, RANK() OVER (ORDER BY srno) rnk
FROM Data
WHERE d_type = 'OPENING'
) opening
LEFT OUTER JOIN
(SELECT
srno SALES_SRNO
, d_date SALES_DATE
, username SALES_USERNAME
, RANK() OVER (ORDER BY srno) rnk
FROM Data
WHERE d_type = 'SALES'
) sales
ON opening.rnk = sales.rnk
LEFT OUTER JOIN
(SELECT
srno PURCHASE_SRNO
, d_date PURCHASE_DATE
, username PURCHASE_USERNAME
, RANK() OVER (ORDER BY srno) rnk
FROM Data
WHERE d_type = 'PURCHASE'
) purchase
ON opening.rnk = purchase.rnk
ORDER BY opening.rnk
;
抱歉 - 无法访问要验证的SQL Server实例。 (经过Oracle测试。)
未使用 TYPE 和 DATE 作为列名,因为它们是SQL保留字。
请评论是否需要调整/进一步详细说明。