2016-10-05 86 views
0
SELECT deposit.numberSuccessfulDeposits, count(distinct userid) 
FROM deposit WHERE deposit.asOfDate between '2016-04-01 00:00:00' and '2016-04-03 23:59:59' 
AND deposit.licenseeId = 1306 
GROUP BY deposit.numberSuccessfulDeposits 

樣本輸出集團通過總結變量

numberSuccessfulDeposits  count(distinct userid) 
0 228 
1 878 
2 90 
3 37 
4 17 

然而,如果Bob在週二做出週一1個存3個存款,那麼這將計入這兩個「1」和「3」號的成功存款。

numberSuccessfulDeposits  count(distinct userid) 
0 ## 
1 1 
2 ## 
3 1 
4 ## 

理想的情況下,它應該只對 「4」

numberSuccessfulDeposits  count(distinct userid) 
0 ## 
1 ## 
2 ## 
3 ## 
4 1 

思考算什麼?

回答

0

計算子查詢中的每用戶總和,然後計算主查詢中的總計數。

SELECT totalDeposits, COUNT(*) 
FROM (SELECT userid, SUM(numberOfSuccessfulDeposits) AS totalDeposits 
     FROM deposit 
     WHERE deposit.asOfDate between '2016-04-01 00:00:00' and '2016-04-03 23:59:59' 
     AND deposit.licenseeId = 1306 
     GROUP BY userid) AS subquery 
GROUP BY totalDeposits 
+0

確定。卡米爾G.和巴爾瑪的建議都奏效。現在,我如何將3個以上的存款組合爲3+類別? – eddd83

1

將分組更改爲基於用戶,並對所有存款進行求和。再算上用戶對這些存款的總和每個:

SELECT 
    numberSuccessfulDeposits, 
    COUNT(userid) AS users_count 
FROM (
    SELECT 
    sum(numberSuccessfulDeposits) AS numberSuccessfulDeposits, 
    userid 
    FROM deposit 
    WHERE asOfDate between '2016-04-01 00:00:00' and '2016-04-03 23:59:59' 
    AND licenseeId = 1306 
    GROUP BY userid 
) t 
GROUP BY numberSuccessfulDeposits 

編輯:分組deposints爲0,1,2,3 +類看起來像:

SELECT 
    numberSuccessfulDeposits, 
    COUNT(userid) AS user_count 
FROM (
    SELECT 
    CASE WHEN numberSuccessfulDeposits >= 3 THEN '3+' ELSE numberSuccessfulDeposits::TEXT END AS numberSuccessfulDeposits, 
    userid 
    FROM (
    SELECT 
     sum(numberSuccessfulDeposits) AS numberSuccessfulDeposits, 
     userid 
    FROM deposit 
    WHERE asOfDate between '2016-04-01 00:00:00' and '2016-04-03 23:59:59' 
     AND licenseeId = 1306 
    GROUP BY userid 
    ) t 
) f 
GROUP BY numberSuccessfulDeposits 
+0

我不認爲'DISTINCT'可以和'SUM'一起使用,只能和'COUNT'一起使用。即使可以,也是不對的。如果鮑勃星期一和星期三1筆存款,這隻會計爲1筆存款,而不是2。 – Barmar

+0

是的,它可以與'SUM'一起使用。爲什麼不?後半部分 - 我忘記了數據列,所以你說得對,我已經把它刪除了,謝謝。 –

+0

我以爲這是'COUNT'的一個特殊功能,但我只是查了一下手冊,你說得對 - 它也適用於'AVG','MAX','MIN'等。我不確定*爲什麼*你想總結/平均只有不同的值,而'MAX'和'MIN'我不明白它是如何產生影響的。 – Barmar