2016-05-12 261 views
4

使用MSSQL集結SQL結果,兩個表,然後彙總結果

我有用戶表,和產品表它們認購。這些訂閱是免費(F)或付費(P)。我已經加入了這些表格,使用case語句將F/P值轉換爲數字,然後通過用戶ID彙總這些值,想法是任何只有免費賬戶的人都會有0的總和,至少有一個付費帳戶價值1或更高。我用下面的遠獲得這樣的:

SELECT t1.user_id, SUM(
    CASE 
     WHEN t2.free_paid = 'P' 
      THEN 1 
     ELSE 0 
    END) as highest 
FROM users t1 INNER JOIN accounts t2 
    ON t1.user_id = t2.user_id 
WHERE t2.account = 'A' 
GROUP BY t1.user_id 
ORDER BY t1.user_id 

這將產生類似的結果:

755 2 
1259 2 
2031 1 
3888 0 

這意味着所有的,但3888至少有一個支付賬戶。

但是現在我想簡單地添加這些數據來獲得我們的兩個值,一個是至少有一個付費賬戶的用戶數(例如3個),另一個是隻有免費賬戶的用戶數例)。

我試過聲明兩個變量,例如: @free和@paid,並使用case語句將這些值包裝到子查詢中,然後將其作爲子查詢添加到這些值中,但無法運行。

任何想法?

+1

預期結果是什麼? –

+0

對於上面的數據,付費:3,免費:1 – SwS

回答

3

重新使用查詢從這個問題您可以創建一個CTE(或子查詢),並彙總結果:

;WITH CTE_UserAccounts AS (
    SELECT t1.user_id, SUM(
     CASE 
      WHEN t2.free_paid = 'P' 
       THEN 1 
      ELSE 0 
     END) as highest 
    FROM users t1 INNER JOIN accounts t2 
     ON t1.user_id = t2.user_id 
    WHERE t2.account = 'A' 
    GROUP BY t1.user_id 
) 
SELECT 
    COUNT(CASE WHEN highest > 0 THEN 1 END) AS [Paid], 
    COUNT(CASE WHEN highest = 0 THEN 1 END) AS [Free] 
FROM 
    CTE_UserAccounts; 
+0

這也適用,我很欣賞使用CTE解決這個問題的見解。 – SwS

1
SELECT 
COUNT(DISTINCT CASE WHEN t2.free_paid = 'P' THEN t1.user_id END) as atleast_one_paid, 
COUNT(DISTINCT CASE WHEN t2.free_paid <> 'P' THEN t1.user_id END) as onlyfree 
FROM users t1 
INNER JOIN accounts t2 ON t1.user_id = t2.user_id 
WHERE t2.account = 'A' 
+0

實際上,'onlyfree'將是至少有一個免費賬戶的不同用戶的數量,因爲沒有什麼可以阻止查詢對至少有一個免費賬戶的用戶進行計數並在兩列中至少有一個付費帳戶。 –

1

你可以只環繞你的原始查詢和概括起來

SELECT SUM (case when highest > 0 THEN 1 else 0 END) as UsersWithPaidAccount, 
SUM (case when highest = 0 THEN 1 else 0 END) as UsersWithOnlyFreeAccount 
FROM (SELECT t1.user_id, SUM(
    CASE 
     WHEN t2.free_paid = 'P' 
      THEN 1 
     ELSE 0 
    END) as highest 
FROM users t1 INNER JOIN accounts t2 
    ON t1.user_id = t2.user_id 
WHERE t2.account = 'A' 
GROUP BY t1.user_id) 
as DerivedTable 
+0

這個工程,非常感謝你! – SwS