每条记录的新行

时间:2018-06-12 15:43:28

标签: sql sql-server-2012

我希望结果在满足条件的每个实例中生成一个新行。我正在使用CASE语句,但这不是可行的方法,因为一旦满足第一个条件,它就会停止评估该字段。

SELECT 
Reviews.ReviewID, 
CASE 
    WHEN Score_CorrectID = 0 THEN 'Correct ID Right Party Authentication'  
    WHEN Score_ProperlyIdentified = 0 THEN 'PCA Properly Identified Itself'
    WHEN Score_MiniMiranda = 0 THEN 'Mini-Miranda'          
END AS [Error Type] 
FROM Reviews INNER JOIN PCAs ON Reviews.PCAID = PCAs.PCAID LEFT JOIN 
PCARebuttal ON Reviews.ReviewID = PCARebuttal.ReviewID 
WHERE 
 (Score_CorrectID = 0 OR Score_ProperlyIdentified = 0 OR Score_MiniMiranda = 
0)

这产生了这个:

enter image description here

我想这样:

enter image description here

2 个答案:

答案 0 :(得分:1)

您可以使用case代替union all而不是SELECT Reviews.ReviewID, 'Correct ID Right Party Authentication' AS [Error Type] FROM Reviews INNER JOIN PCAs ON Reviews.PCAID = PCAs.PCAID LEFT JOIN PCARebuttal ON Reviews.ReviewID = PCARebuttal.ReviewID WHERE Score_CorrectID = 0 UNION ALL SELECT Reviews.ReviewID, 'PCA Properly Identified Itself' AS [Error Type] FROM Reviews INNER JOIN PCAs ON Reviews.PCAID = PCAs.PCAID LEFT JOIN PCARebuttal ON Reviews.ReviewID = PCARebuttal.ReviewID WHERE Score_ProperlyIdentified = 0 UNION ALL SELECT Reviews.ReviewID, 'Mini-Miranda' AS [Error Type] FROM Reviews INNER JOIN PCAs ON Reviews.PCAID = PCAs.PCAID LEFT JOIN PCARebuttal ON Reviews.ReviewID = PCARebuttal.ReviewID WHERE Score_MiniMiranda = 0

cat composer.json

答案 1 :(得分:1)

使用apply

SELECT r.ReviewID, v.error_type
FROM Reviews r INNER JOIN
     PCAs
     ON r.PCAID = PCAs.PCAID LEFT JOIN 
     PCARebuttal pr
     ON r.ReviewID = pr.ReviewID OUTER APPLY
     (SELECT *
      FROM (VALUES (Score_CorrectID, 'Correct ID Right Party Authentication'),  
                   (Score_ProperlyIdentified, 'PCA Properly Identified Itself'),
                   (Score_MiniMiranda, 'Mini-Miranda')
           ) v(score, error_type)
      WHERE score = 0
     ) v        
WHERE (Score_CorrectID = 0 OR Score_ProperlyIdentified = 0 OR Score_MiniMiranda = 0);

那就是说,我可能只是将值连接成一列:

SELECT r.ReviewID,
       ( (CASE WHEN Score_CorrectID = 0 THEN 'Correct ID Right Party Authentication; ' ELSE '' END) +  
         (CASE WHEN Score_ProperlyIdentified = 0 THEN 'PCA Properly Identified Itself; ' ELSE '' END) +
         (CASE WHEN Score_MiniMiranda = 0 THEN 'Mini-Miranda;' ELSE '' END)
       ) as error_types
FROM Reviews r INNER JOIN
     PCAs
     ON r.PCAID = PCAs.PCAID LEFT JOIN 
     PCARebuttal pr
     ON r.ReviewID = pr.ReviewID OUTER APPLY
     (SELECT *
      FROM (VALUES ()
           ) v(score, error_type)
      WHERE score = 0
     ) v        
WHERE (Score_CorrectID = 0 OR Score_ProperlyIdentified = 0 OR Score_MiniMiranda = 0);