sqlsql-server

SUM for multiple condition with 2 tables in one query


So I would like to get the first and last name and the count of viewed players present in column Viewed_PlayerID of table ViewedPlayers of each user, whose userID is present in column CreatedByCharacterID of table ViewedPlayers. Of which the viewed_playerID is marked as "teamplayer" in column UserType of table Users.

Table Users:

ID UserType Firstname LastName
11 Fan FirstN_TP1 LastN_TP1
12 Fan FirstN_TP2 LastN_TP2
20 Fan FirstN_TP3 LastN_TP3
53 Teamplayer FirstN_TP4 LastN_TP4
25 Fonske FirstN_TP5 LastN_TP5
31 Speedy FirstN_TP6 LastN_TP6
60 Teamplayer FirstN_TP7 LastN_TP7
61 Teamplayer FirstN_TP8 LastN_TP8
54 Coach FirstN_TP9 LastN_TP9
70 Teamplayer FirstN_TP10 LastN_TP10
56 Coach FirstN_TP11 LastN_TP11
59 Teamplayer FirstN_TP12 LastN_TP12
63 Teamplayer FirstN_TP13 LastN_TP13
64 Teamplayer FirstN_TP14 LastN_TP14
65 Teamplayer FirstN_TP15 LastN_TP15
66 Teamplayer FirstN_TP16 LastN_TP16
67 Teamplayer FirstN_TP17 LastN_TP17
71 Teamplayer FirstN_TP18 LastN_TP18
72 Coach FirstN_TP19 LastN_TP19
73 CBM FirstN_TP20 LastN_TP20
74 Teamplayer FirstN_TP21 LastN_TP21
75 Teamplayer FirstN_TP22 LastN_TP22

Table ViewedPlayers:

Viewed_PlayerID CreatedByCharacterID
61 20
60 20
59 20
59 31
61 25
65 20
64 25
65 25
60 25
64 20
67 25
59 12
70 11
61 12
56 20
75 31

Expected result:

Firstname LastName Count
FirstN_TP3 LastN_TP3 5
FirstN_TP5 LastN_TP5 5
FirstN_TP6 LastN_TP6 2
FirstN_TP2 LastN_TP2 2
FirstN_TP1 LastN_TP1 1

I tried 2 different queries

Query #1:

SELECT      
    c.Firstname, c.LastName,
    SUM(CASE WHEN p.CreatedByCharacterID THEN 1 ELSE 0 END) AS Count
FROM 
    Users c
JOIN    
    ViewedPlayers p ON p.CreatedByCharacterID = c.ID
WHERE   
    c.UserType = 'Teamplayer'
GROUP BY 
    p.CreatedByCharacterID
ORDER BY 
    SUM(CASE WHEN p.CreatedByCharacterID THEN 1 ELSE 0 END) DESC

Query #2:

SELECT      
    c.Firstname, c.LastName,
    SUM(CASE WHEN c. UserType = 'Teamplayer' AND p.CreatedByCharacterID THEN 1 ELSE 0 END) AS Count
FROM    
    Users c
JOIN
    ViewedPlayers p ON p.CreatedByCharacterID = c.ID
GROUP BY 
    p.CreatedByCharacterID
ORDER BY 
    SUM(CASE WHEN p.CreatedByCharacterID THEN 1 ELSE 0 END) DESC

Solution

  • Your query just needs two separate references to the Users table. One to get the viewer's name, and one to get the viewee's UserType.

    SELECT
        u.Firstname,
        u.LastName,
        COUNT(*) 
    FROM
        Users           AS u
    INNER JOIN
        ViewedPlayers   AS vp
            ON vp.CreatedByCharacterID = u.ID
    INNER JOIN
        Users           AS p
            ON vp.Viewed_PlayerID      = p.ID
    WHERE
        p.UserType = 'Teamplayer'
    GROUP BY
        u.Firstname,
        u.LastName
    ORDER BY
       COUNT(*) DESC