2

我有一个具有以下值的 sql 表

       |  col1 | col2|   source |  values
       |  1    |  2  |  A       |   null
       |  1    |  2  |  B       |   1.0
       |  1    |  2  |  C       |   null
       |  1    |  4  |  A       |   2.0
       |  1    |  4  |  B       |   2.0
       |  1    |  4  |  C       |   2.0
       |  1    |  5  |  A       |   null
       |  1    |  5  |  B       |   null
       |  1    |  5  |  C       |   null

我怎样才能得到一个输出组col1col2一个标志:

  • 所有值都匹配一个组(标志 = 1)
  • 所有值均为空(标志 = 2)
  • 一些值为空(标志 = 3)

输出:

       |  col1 | col2|   flag
       |  1    |  2  |   3
       |  1    |  4  |   1
       |  1    |  5  |   2
4

3 回答 3

3

或者:根据您更新的问题:

  SELECT 
    col1, 
    col2,
    SUM(CASE WHEN SomeConditionHere THEN 1 ELSE 0 END) AS Flag
  FROM Table1
  GROUP BY col1, col2;

SQL 小提琴演示

这会给你:

| COL1 | COL2 | FLAG |
----------------------
|    1 |    2 |    2 |
|    1 |    4 |    0 |
|    1 |    5 |    3 |

请注意:我假设标志是列中有多少NULL个值VALUES,所以我使用"Values" IS NULL而不是SomeConditionHere.

我不明白flag应该如何在您发布的预期结果中计算 。您必须使用定义标志的谓词而不是"Values" IS NULL.

更新:

试试这个:

WITH Flags
AS
(
  SELECT 
    col1, col2,
    COUNT(*) ValuesCount,
    SUM(CASE WHEN "Values" IS NULL THEN 1 ELSE 0 END) AS NULLValues
  FROM Table1 
  GROUP BY col1, col2
)
SELECT 
  col1,
  col2,
  Flag = CASE WHEN ValuesCount = NULLValues THEN 2
              WHEN NULLVALUES = 0 
               AND ValuesCount = (SELECT COUNT(*) 
                                  FROM Table1 t2
                                  WHERE t1.col1 = t2.col1
                                    AND t1.col2 = t2.col2) THEN 1
               ELSE 3
END
FROM Flags t1;

更新的 SQL Fiddle 演示

这会给你:

| COL1 | COL2 | FLAG |
----------------------
|    1 |    2 |    3 |
|    1 |    4 |    1 |
|    1 |    5 |    2 |
于 2013-01-14T08:44:49.337 回答
3

在 SQLServer2005+

;WITH cte AS
 (
  SELECT col1, col2, [values],       
         COUNT(CASE WHEN [values] IS NULL THEN 1 END) OVER(PARTITION BY col1, col2) AS cntNULL,
         COUNT(*) OVER(PARTITION BY col1, col2) AS cntCol
  FROM dbo.test5
  )
  SELECT col1, col2, MAX(CASE WHEN cntNULL = 0 THEN 1
                              WHEN cntNULL = cntCol THEN 2
                              ELSE 3 END) AS flag
  FROM cte
  GROUP BY col1, col2  

SQLFiddle上的演示

于 2013-01-14T09:23:08.990 回答
2

...如果您想要更便携,那么没有 CTE 的解决方案SQL

select col1,
       col2,
        case 
            when DistinctValuesWithoutNulls = 1 and NullCount = 0 then 1 
            when DistinctValuesWithoutNulls = 0 then 2
            when NullCount > 0 then 3
        end flag
from
(
    select  col1, 
            col2, 
            count(distinct [values]) DistinctValuesWithoutNulls, 
            sum(case when [values] is null then 1 else 0 end) NullCount
    from Table1
    group by col1, col2
) tmp
于 2013-01-14T10:07:11.123 回答