DECLARE @t TABLE (AdrNr INT, Nr1 INT, Nr2 INT, Nr3 INT, Nr4 INT, Nr5 INT, Nr6 INT, Nr7 INT)
INSERT INTO @t
VALUES (500, 3, 4, 8, 42, 5, 76, 91)
SELECT AdrNr, a
FROM @t
CROSS APPLY (
VALUES
('Nr1', Nr1),
('Nr2', Nr2),
('Nr3', Nr3),
('Nr4', Nr4),
('Nr5', Nr5),
('Nr6', Nr6),
('Nr7', Nr7)
) t(a, b)
WHERE b = 8
輸出 -
AdrNr a
----------- ----
500 Nr3
我的價值觀後:Is UNPIVOT the best way for converting columns into rows?
UPDATE(動態SQL):
DECLARE @t TABLE (AdrNr INT, Nr1 INT, Nr2 INT, Nr3 INT, Nr4 INT, Nr5 INT, Nr6 INT, Nr7 INT)
INSERT INTO @t
VALUES
(500, 3, 4, 8, 42, 5, 76, 91),
(501, 3, 8, 8, 42, 5, 76, 91)
IF OBJECT_ID('tempdb.dbo.#tbl') IS NOT NULL
DROP TABLE #tbl
SELECT AdrNr, t.col, t.val
INTO #tbl
FROM @t
CROSS APPLY (
VALUES
('Nr1', Nr1), ('Nr2', Nr2), ('Nr3', Nr3), ('Nr4', Nr4),
('Nr5', Nr5), ('Nr6', Nr6), ('Nr7', Nr7)
) t(col, val)
WHERE val = 8
DECLARE @SQL NVARCHAR(MAX)
SET @SQL = '
SELECT *
FROM #tbl
PIVOT (
MAX(val)
FOR col IN (' + STUFF((
SELECT DISTINCT ', [' + col + ']'
FROM #tbl
FOR XML PATH('')), 1, 2, '') + ')
) p'
EXEC sys.sp_executesql @SQL
輸出 -
AdrNr Nr2 Nr3
----------- ----------- ---------
500 NULL 8
501 8 8
'UNPIVOT'使列行和'SELECT ... WHERE'。或結合整個條件,如'Nr1 = 8或Nr2 = 8或...'。沒有你演示的這種語法。 –