Group by clause

  • I have a table like below:

    ClientId ClientName Versionsource

    1 X David

    2 y Manual

    3 Z Richard

    4 A Manual

    5 B David

    Now i want to group the records on the basiss of VersionSoruce in the way if it's not Manual then it will come in 'Auto' Category, Means the records should be grouped in two groups only i.e. Manual and Auto.

  • try using UNION

    SELECT ClientId, ClientName, Versionsource

    FROM YourTable

    WHERE Versionsource = 'Manual'

    Union

    SELECT ClientId, ClientName, 'Auto' as Versionsource

    FROM YourTable

    WHERE Versionsource 'Manual'

  • Or CASE

    USE tempDB

    GO

    CREATE TABLE

    X

    (ClientIdINT,

    ClientNameVARCHAR(50),

    VersionsourceVARCHAR(50))

    INSERT X

    (ClientId,

    ClientName,

    Versionsource)

    SELECT 1, 'X', 'David' UNION

    SELECT 2, 'y', 'Manual' UNION

    SELECT 3, 'Z', 'Richard' UNION

    SELECT 4, 'A', 'Manual' UNION

    SELECT 5, 'B', 'David'

    SELECT

    CASE

    WHEN VersionSource = 'Manual' THEN 'Manual'

    ELSE 'Auto'

    END AS VersionSource,

    COUNT(*) AS MyCount

    FROM

    X

    GROUP BY

    CASE

    WHEN VersionSource = 'Manual' THEN 'Manual'

    ELSE 'Auto'

    END

  • Thanks Steve for ur quick response, but whether there is any way to do that work with Group by clause instead of Union?

  • Thanks a lot Allen that's the query i exactly wanted.

  • No problem. CASE is hugely powerful and can be used in loads of places/problems.

Viewing 6 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic. Login to reply