简体   繁体   中英

How to avoid duplicates for SUM( CASE WHEN ..THEN 1 ELSE 0 END)?

I ghave following query:

            SELECT col.myId,
                   SUM( CASE WHEN tu.userId IS NOT NULL THEN 1  ELSE 0 END) AS uCount,
                   SUM( CASE WHEN g.grouptype != 12 THEN 1  ELSE 0 END) AS gCount
            FROM myUserTable col
                     LEFT JOIN fooTable elem ON col.myId = elem.myId
                     LEFT JOIN barTable esc ON elem.anotherId = esc.anotherId
                     LEFT JOIN userTable tu ON esc.anotherId = tu.anotherId
                     LEFT JOIN grouTable g ON g.groupid = tu.groupid
            GROUP BY col.myId

The problem here that duplicated userId is counted twice. I want to avoid it.

How can I achieve it?

Perhaps you want COUNT(DISTINCT) ?

COUNT(DISTINCT tu.userId) AS uCount,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM