У меня есть таблица примерно так:

stuff          type      price

first_stuff     1       43
second_stuff    2       46
third_stuff     3       24
fourth_stuff    2       12
fifth_stuff     NULL    90

И каждому type материала присваивается описание, которое не хранится в БД.

1 = Bad
2 = Good
3 = Excellent 
NULL = Not_Assigned

Все, что я хочу, - это вернуть таблицу, в которой count каждая type отдельно, например:

Description      Count

Bad              1
Good             2
Excellent        1
Not_Assigned     1
2
Dan Paschevici 29 Дек 2015 в 12:40

4 ответа

Лучший ответ
DECLARE @t TABLE ([type] INT)

INSERT INTO @t ([type])
VALUES (1),(2),(3),(2),(NULL)

SELECT
    [Description] =
        CASE t.[type]
            WHEN 1 THEN 'Bad'
            WHEN 2 THEN 'Good'
            WHEN 3 THEN 'Excellent'
            ELSE 'Not_Assigned'
        END, t.[Count]
FROM (
    SELECT [type], [Count] = COUNT(*)
    FROM @t
    GROUP BY [type]
) t
ORDER BY ISNULL(t.[type], 999)

Выход -

Description  Count
------------ -----------
Bad          1
Good         2
Excellent    1
Not_Assigned 1
2
Devart 29 Дек 2015 в 09:43

Если вы используете Sql server 2012+, используйте это

SELECT
    [Description] = coalesce(choose (t.[type],'Bad','Good' ,'Excellent'), 'Not_Assigned'),
     t.[Count]
FROM (
    SELECT [type], [Count] = COUNT(*)
    FROM yourtable
    GROUP BY [type]
) t
1
Pரதீப் 29 Дек 2015 в 09:55
;WITH CTE_TYPE
     AS (SELECT DESCRIPTION,
                VALUE
         FROM   (VALUES ('BAD',
                1),
                        ('GOOD',
                2),
                        ('EXCELLENT',
                3))V( DESCRIPTION, VALUE )),
     CTE_COUNT
     AS (SELECT C.DESCRIPTION,
                Count(T.TYPE) TYPE_COUNT
         FROM   YOUR_TABLE T
                JOIN CTE_TYPE C
                  ON T.TYPE = C.VALUE
         GROUP  BY TYPE,
                   DESCRIPTION
         UNION ALL
         SELECT 'NOT_ASSIGNED' AS DESCRIPTION,
                Count(*)       TYPE_COUNT
         FROM   YOUR_TABLE
         WHERE  TYPE IS NULL)
SELECT *
FROM   CTE_COUNT 
2
NewSQL 29 Дек 2015 в 11:35

Надеюсь это поможет.

SELECT ISNULL(D.descr, 'Not_Assigned'),
       T2.qty
FROM
    (SELECT T.type,
            COUNT(*) as qty
    FROM Table AS T
    GROUP BY type) AS T2
    LEFT JOIN (SELECT 1 as type, 'Bad' AS descr
               UNION ALL
               SELECT 2, 'Good'
               UNION ALL
               SELECT 3, 'Excellent') AS D ON D.type = T2.type
1
fabulaspb 29 Дек 2015 в 09:47