2017-06-05 58 views
-2

我有很多這樣的數據,在這裏我只給出樣本數據,所以情況下條款不適合這個,如何解決以下情況,使用SQL服務器?

DECLARE @T TABLE (EID INT, VALUE VARCHAR(50),CATEGORY VARCHAR(50),CATEGORY1 VARCHAR(50)) 

INSERT INTO @T 
SELECT 1,'JHON','NAME',NULL 
UNION 
SELECT 2,'MARY','NAME',NULL 
UNION 
SELECT 1,'IT','DEPT',NULL 
UNION 
SELECT 1,'85204-00065',NULL,'PHONE' 
UNION 
SELECT 1,'MALE',NULL,'GENDER' 
UNION 
SELECT 2,'85285-00525',NULL,'PHONE' 
UNION 
SELECT 2,'FEMALE',NULL,'GENDER' 
UNION 
SELECT 2,'BPO','DEPT',NULL 

SELECT * FROM @T 

預期輸出:

EId Name Dept Gender Phone 
1 Jhon IT  Male 85204-00065 
2 Mary Bpo  Female 85285-00525 

任何一個提供更好的此場景的解決方案。

+1

我看不到行之間的任何關係...... – Prisoner

+2

看起來像一些變種[EAV(https://開頭的連接。 wikipedia.org/wiki/Entity-attribute-value_model)。通常在外部專家場景中皺眉。 –

回答

1

假設類別和CATEGORY1是互斥的(如果不是要弄清這個問題),那麼你可以使用:

SELECT * 
FROM (
    SELECT x.EID, x.VALUE, ISNULL(x.CATEGORY, x.CATEGORY1) AS NEW_CATEGORY 
    FROM @T AS x 
    WHERE x.CATEGORY IN ('NAME', 'DEPT', 'GENDER') 
    OR x.CATEGORY1 IN ('NAME', 'DEPT', 'GENDER') 
) y 
PIVOT(MAX(y.VALUE) FOR y.NEW_CATEGORY IN ([NAME], [DEPT], [GENDER])) AS z 

注:這個設計很奇怪(至少說了)。我沒有看到名爲CATEGORY和CATEGORY1的兩列的理由。

+0

感謝波格丹,我有很多像分類和類別1的列,所以上面的解決方案不能適合我的場景 –

+0

你告訴我,也有CATEGORY2,CATEGORY3等......直到CATEGORY1000? –

+0

完全是這樣的 –

0

你可以做支點,凝聚和如下動態查詢:

declare @cols1 varchar(max) 
declare @cols2 varchar(max) 
declare @query nvarchar(max) 

Select @cols1 = stuff((select Distinct ','+QuoteName(Coalesce(Category,Category1)) from YourEmpData for xml path('')),1,1,'') 
Select @Cols2 = 'Coalesce(' +stuff((Select ','+ QUOTENAME(Column_Name) from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'YourEmpData' and COLUMN_NAME not in ('EID', 'VALUE') for xml path('')),1,1,'') + ')' 

Select @query = ' Select * from (
     Select EID, [Value], ' + @cols2 + ' as Categories FROM YourEmpData) a 
     pivot (max([Value]) for [Categories] in (' + @cols1 + ')) p ' 

select @query --uncomment and execute if your query generated correct 
--exec sp_executesql @query 
相關問題