しかし、あなたは、この要件の正確な目的が何であるかをしたい
サンプルデータ:
DECLARE @Table1 TABLE
(Name varchar(2), Family varchar(2), R varchar(2), C int, D varchar(1))
;
INSERT INTO @Table1
(Name, Family, R, C, D)
VALUES
('N1', 'F1', 'S1', 1, 'A'),
('N2', 'F2', 'S2', 2, 'A'),
('N3', 'F3', 'S1', 1, 'B'),
('N4', 'F4', 'S2', 2, 'B'),
('N5', 'F5', 'S3', 3, 'A')
;
スクリプト
;with CTE as (
SELECT D,
[S1],
[S2],
[S3]
FROM (
select Name,
Family,
R,
C,
D
FROM @Table1)t
PIVOT (MAX(Name) For R in ([S1],[S2],[S3])
)pvt
GROUP BY D,[S1],[S2],[S3])
,
CTE2 AS (
SELECT D,
[S1],
[S2],
[S3]
FROM (
select Name,
Family,
R,
C,
D FROM @Table1)t
PIVOT (MAX(Family) For r in ([S1],[S2],[S3])
)pvt
GROUP BY D,[S1],[S2],[S3])
Select
CASE WHEN RN = 1 THEN D ELSE NULL END NAME ,S1,S2,S3 FROM (
Select *,
Row_number()OVER(PARTITION BY D ORDER BY (SELECT NULL))RN from (
SELECT D,
(SELECT S1 FROM cte where S1 IS NOT NULL AND C.D = D)S1,
(SELECT S2 FROM cte where S2 IS NOT NULL AND C.D = D)S2,
(SELECT S3 FROM cte where S3 IS NOT NULL AND C.D = D)S3 FROM CTE C
UNION
SELECT D,
(SELECT S1 FROM CTE2 where S1 IS NOT NULL AND C.D = D)S1,
(SELECT S2 FROM CTE2 where S2 IS NOT NULL AND C.D = D)S2,
(SELECT S3 FROM CTE2 where S3 IS NOT NULL AND C.D = D)S2 FROM cte2 C)T)TT
はStackOverflowのへようこそ。 [ask]をお読みください –
必要なテーブルを作成できない問題を指定できますか? – Fabio