如何解决以下场景,使用SQL服务器?

时间:2017-06-05 09:51:21

标签: sql sql-server

我有很多像这样的数据,这里我只给出了样本数据,所以当Case子句不适合这个时,

  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

任何一个为这种情况提供更好的解决方案。

2 个答案:

答案 0 :(得分:1)

假设CATEGORY和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。

答案 1 :(得分: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