检查错误:分组依据

时间:2018-05-28 13:16:45

标签: sql sql-server group-by grouping

我收到了一个查询,我想检查特定号码是否有任何错误(否)。如果有1个或更多错误,结果应为"是"。如果没有错误,结果应为" no"。但我想要每行只有1行,而不是多行。

请参阅以下查询以及我希望的结果:

SELECT CASE WHEN ISNUMERIC(SUB1.ItemNo) != 1 THEN 'ERROR: ItemNo not numeric'
           ELSE 'OK'
       END AS ErrorType, SUB1.No
FROM
(
--123
    SELECT 123 AS No, '123456789' AS ItemNo
    UNION ALL
    SELECT 123 AS No, '123456789x' AS ItemNo
    UNION ALL
    SELECT 123 AS No, '122456789' AS ItemNo
    UNION ALL
--456
    SELECT 456 AS No, '123456789' AS ItemNo
    UNION ALL
    SELECT 456 AS No, '178978788' AS ItemNo
    UNION ALL
    SELECT 456 AS No, '114147787' AS ItemNo
) AS SUB1

- 结果:最终应该如何看待

SELECT 'Yes' AS Error, 123 AS No
UNION ALL
SELECT 'No' AS Error, 456 AS No

1 个答案:

答案 0 :(得分:0)

您可以使用聚合:

SELECT (CASE WHEN MIN(ISNUMERIC(SUB1.ItemNo)) = 0 THEN 'ERROR: ItemNo not numeric'
             ELSE 'OK'
        END) AS ErrorType,
       SUB1.No
FROM (SELECT 123 AS No, '123456789' AS ItemNo
      UNION ALL
      SELECT 123 AS No, '123456789x' AS ItemNo
      UNION ALL
      SELECT 123 AS No, '122456789' AS ItemNo
      UNION ALL
      SELECT 456 AS No, '123456789' AS ItemNo
      UNION ALL
      SELECT 456 AS No, '178978788' AS ItemNo
      UNION ALL
      SELECT 456 AS No, '114147787' AS ItemNo
     ) SUB1
GROUP BY SUB1.NO;

在此上下文中,MIN()仅检查是否有任何数值。