Search code examples
sqlcountssms

Count with GroupBY does not count the actual number of records, shows as 1 only


I have this simple sample that I'm working with. I have 2 records that are the same, and I'm just trying to roll these two records up so that it shows 2 as count since X and Y are exact

WITH test AS (
    SELECT '11' AS X, 'BYE'AS y
    UNION
    SELECT '11' AS X, 'BYE' AS Y
)

SELECT x, y, COUNT(x)
FROM test
GROUP BY x,y

Solution

  • The problem has nothing to do with the COUNT nor the GROUP BY and everything to do with your UNION. Your CTE (test) only provides one row as a UNION query returns distinct rows and you only have one distinct row. Use UNION ALL:

    WITH test AS (
        SELECT '11' AS X, 'BYE'AS y
        UNION ALL
        SELECT '11' AS X, 'BYE' AS Y
    )
    SELECT x, y, COUNT(x)
    FROM test
    GROUP BY x,y;
    

    Better yet, don't use that old style and use a VALUES table construct:

    WITH test AS(
        SELECT x,y
        FROM (VALUES(11,'BYE'),
                    (11,'BYE'))V(x,y))
    SELECT x, y, COUNT(x)
    FROM test
    GROUP BY x,y;