2014-07-17 153 views
0

我完全丧失了如何执行此操作。我一直在绞尽脑汁去冲刷互联网,但我不认为有任何“简单”解决方案。SQL Server - 跨所有列计数记录具有相同的值

我希望能够在多个列之间具有相同的值时对给定用户ID的出现次数进行计数。并不是所有的列都有记录,但是任何记录中所有非空值的列具有相同值的记录都是我想要记录的记录。我在下面提供了一个例子。

注意:我可以在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); 
+0

这是对SQL Server或MS访问?这些是非常不同的数据库。 –

+0

两者都可以工作。我试图添加两个作为标签,它不喜欢, – user3150260

回答

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; 
+0

谢谢。我不熟悉coalesce,我会读一读。所以,我的例子是我实际上正在做的事情的简明版本。它可能涉及20个问题和数千条记录。你认为这仍然是可行的吗? – user3150260

+0

@ user3150260。 。 。如果你没有在列中存储相似的值,而是将它们放在行中,你会发现这更容易。但是,是的,只要为每行添加一个条件,就可以将其扩展到更多列。 –

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] 
相关问题