[英]SQL Server - Counting records with same value across all columns
我完全不知道该怎么做。 我一直在绞尽脑汁,搜寻互联网,但我认为没有任何“简单”的解决方案。
当多个列中的值相同时,我希望能够计算给定userID的出现次数。 并非所有列都具有一条记录,但是我希望在计数中捕获的是所有不为null的所有具有相同值的记录。 我在下面提供了一个示例。
注意:我可以在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);
您可以这样做:
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;
如果您先将数据标准化,
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.