Select with case not included in group by

  • Hello,

    In following query there is a CASE sentence in SELECT clause but it isn't placed in GROUP BY.

    I've two:

    1. Why there is no "group by" error?
    2.  Why results of query WITHOUT CASE in GROUP BY are the same as a query WITH CASE in GROUP BY clause?
    SELECT
    [Names],
    [CardType],
    count(*) as NumberOfRows,
    CASE Names
    WHEN 'A' THEN 'Class 1'
    WHEN 'B' THEN 'Class 2'
    WHEN 'C' THEN 'Class 3'
    WHEN 'D' THEN 'Class 4'
    END as 'Classes'
    FROM [dbo].[_MyBase]
    GROUP BY [Names], [CardType]
    --, CASE Names
    -- WHEN 'A' THEN 'Class 1'
    -- WHEN 'B' THEN 'Class 2'
    -- WHEN 'C' THEN 'Class 3'
    -- WHEN 'D' THEN 'Class 4'
    -- END
    ORDER BY [Names], [CardType]
  • (1) Because every non-aggregated column in your SELECT list appears in your GROUP BY clause

    (2) Because the CASE expression doesn't have any effect on the Names, CardType partitions

    John

  • Hello,

     

    DECLARE @_MyBase TABLE
    (
    Names NVARCHAR(15),
    CardType INT
    )

    INSERT INTO @_MyBase
    VALUES('A','1'),('B','1'),('C','1'),('D','1')

    SELECT
    NAMES,
    CardType
    ,count(*) as NumberOfRows
    , CASE Names
    WHEN 'A' THEN 'Class 1'
    WHEN 'B' THEN 'Class 2'
    WHEN 'C' THEN 'Class 3'
    WHEN 'D' THEN 'Class 4'
    END Classes
    FROM @_MyBase
    GROUP BY [Names], [CardType]

    Allah bize yeter, O ne güzel vekildir.

    vedatoozer@gmail.com

  • Thank you very much for your answers!

Viewing 4 posts - 1 through 3 (of 3 total)

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