SQL Server - 计算所有列中具有相同值的记录

时间:2014-07-17 15:27:56

标签: sql sql-server

我完全不知道如何做到这一点。我一直绞尽脑汁搜索互联网,但我认为没有任何“简单”的解决方案。

我希望能够在多个列中存在相同值时计算给定userID的出现次数。并非所有列都有记录,但是任何记录中所有非空的具有相同值的列都将是我想要在计数中捕获的记录。我在下面提供了一个例子。

注意:我可以在SQL Server或Access中运行它。

Current Table:
CREATE TABLE INFO_TABLE 
    ([UID] int, [Question1] int, [Question2] int, [Question3] int, [Question4] int, [Question5] int)
;


INSERT INTO INFO_TABLE 
    ([UID], [Question1], [Question2], [Question3], [Question4], [Question5])
VALUES
    (100, 5, 5, 5, 5, 5),
    (100, 5, 5, 4, 4, 5),
    (100, 3, 5, 5, 5, 5),
    (200, 5, 5, 5, 5, 5),
    (200, , 1, 1, 1, 1),
    (100, 5, 5, 5, 5, 5),
    (300, 4, 4, 4, 4, 4),
    (400, 5, 5, 3, 3, 5),
    (400, 5, 5, 4, 5, 5),
    (300, 5, 5, 5, 5, );

期望的结果:

CREATE TABLE INFO_TABLE 
    ([UID] int, [CountFlat] int)


INSERT INTO INFO_TABLE 
    ([UID], [CountFlat])
VALUES
    (100, 2),
    (200, 2),
    (300, 2),
    (400, 0);

2 个答案:

答案 0 :(得分:2)

您可以这样做:

select id, count(*)
from info_table
where coalesce(question1, question2, question3, question4, question5) = coalesce(question2, question3, question4, question5, question1) and
      coalesce(question1, question2, question3, question4, question5) = coalesce(question3, question4, question5, question1, question2) and
      coalesce(question1, question2, question3, question4, question5) = coalesce(question4, question5, question1, question2, question3) and
      coalesce(question1, question2, question3, question4, question5) = coalesce(question5, question1, question2, question3, question4)
group by id;

答案 1 :(得分:0)

如果您首先将数据标准化,

create table INFOTABLE_normalized
  ([UID] int, [QUESTION_SET_ID] int, [QUESTION_NUM] int, [QUESTION] int)

然后,查询就会逐字逐句重述原始问题:

with sets_with_only_one_distinct_question AS (
  select
    [UID]
   ,[QUESTION_SET_ID]
  from INFOTABLE_normalized
  where [QUESTION] is not NULL
  group by [UID],[QUESTION_SET_ID]
  having COUNT(DISTINCT [QUESTION]) = 1
)
select 
  [UID]
 ,COUNT([QUESTION_SET_ID]) AS [COUNT_FLAT]
from sets_with_only_one_distinct_question
group by [UID]