如何在SQL Server中将数据行转换为列

时间:2019-02-08 09:29:53

标签: sql-server

我想使数据行到SQL Server中的列,在这种情况下,我使用数据透视,但结果为null。这是我使用数据透视表之前的数据

enter image description here

使用透视后,结果如下:

enter image description here

这是我的查询:

SELECT 
    *  
FROM   
    (SELECT 
         A.asset, 
         A.inspection_title, 
         A.question, A.answer, 
         (LEFT(CONVERT(VARCHAR, a.assign_date, 101), 6) 
              + RIGHT(Year(a.assign_date), 2)) AS [datee] 
     FROM   
         vw_amtiss_inspection_answers A 
     JOIN 
         vw_asset_r B ON a.asset = b.asset_code 
     WHERE  
         A.inspection_code LIKE '%-DC-%' 
         AND b.equip_grp_id = 'HD7857' 
         AND a.asset = 'DT7014' 
         AND A.assign_date IN (SELECT TOP 5 A.assign_date 
                               FROM vw_amtiss_inspection_answers A 
                               JOIN vw_asset_r B ON a.asset = b.asset_code 
                               WHERE A.inspection_code LIKE '%-DC-%' 
                                 AND b.equip_grp_id = 'HD7857' 
                                 AND a.asset = 'DT7014' 
                               GROUP BY a.assign_date 
                               ORDER  BY a.assign_date DESC) 
    GROUP BY 
        a.asset, a.inspection_title, 
        a.question, a.answer, 
        b.equip_grp_id, a.assign_date) C 
PIVOT 
    (MIN(answer) 
        FOR datee IN (jawaban_1, jawaban_2, jawaban_3, 
                      jawaban_4, jawaban_5)) AS p

请帮助我解决此问题。谢谢

1 个答案:

答案 0 :(得分:0)

由于您的数据仍然是图像,因此我没有正确转录此图像。但是,这足以让您获得所需的答案:

WITH VTE AS(
    SELECT 'DT7014' AS Col1,
           'Daily Check' As Col2,
           'Water Level' AS Question,
           'Ok' AS Answer,
           CONVERT(date,'20190206') AS [Date]
     UNION ALL
     SELECT 'DT7014' AS Col1,
           'Daily Check' As Col2,
           'Water Level' AS Question,
           NULL AS Answer,
           '20190215' AS [Date]),
CTE AS(
    SELECT VTE.Col1,
           VTE.Col2,
           VTE.Question,
           VTE.Answer,
           VTE.[Date],
           ROW_NUMBER() OVER (PARTITION BY Col1, VTE.Col2, VTE.Question ORDER BY [Date]) AS RN
    FROM VTE)
SELECT C.Col1,
       C.Col2,
       C.Question,
       MAX(CASE C.RN WHEN 1 THEN Answer END) AS J1,
       MAX(CASE C.RN WHEN 2 THEN Answer END) AS J2
FROM CTE C
GROUP BY C.Col1,
         C.Col2,
         C.Question;

有一个警告。您的图像强烈暗示,您的列datee不是数据类型date,而是数据类型varchar。如果是这样,上述方法将无法正常工作。例如,对于日期,语句'20181219' < '20190104'为true,但是对于数据,语句'12/19/18' < '04/01/19'为false('1' > '0',因此varchar 表示形式 2018年12月19日>是在日期{em> 2019年1月4日的varchar之后。解决此问题的方法是修复表中的数据类型。 varchar不是 一种“适合所有数据类型的大小”。