2014-07-17 154 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] 
相關問題