根据范围从同一个表中的两个不同列计数

时间:2016-06-27 08:26:05

标签: sql

我有这样的标准:

MONTHS  CUST    CATEGORY
10       1          1
20       2          1
10       3         NULL
30       4          1
40       5          NULL

我想根据范围计算不属于禁止和不属于类别。

例如:
在10-19范围内,没有任何人将是2,类别将是1。 请帮忙。

3 个答案:

答案 0 :(得分:1)

您可以使用如下查询:

SELECT CASE 
            WHEN MONTHS BETWEEN 10 AND 19 THEN '10-19'
            WHEN MONTHS BETWEEN 20 AND 29 THEN '20-29'
            WHEN MONTHS BETWEEN 30 AND 39 THEN '30-39'
            WHEN MONTHS BETWEEN 40 AND 49 THEN '40-49'
            ELSE '50-'
         END,
         COUNT(CUST) AS CUST_COUNT,
         COUNT(CATEGORY) AS CATEGORY_COUNT
FROM mytable
GROUP BY CASE 
            WHEN MONTHS BETWEEN 10 AND 19 THEN '10-19'
            WHEN MONTHS BETWEEN 20 AND 29 THEN '20-29'
            WHEN MONTHS BETWEEN 30 AND 39 THEN '30-39'
            WHEN MONTHS BETWEEN 40 AND 49 THEN '40-49'
            ELSE '50-'
         END

答案 1 :(得分:1)

只要分组表达式可以计算整个RANGE的相同值,就可以使用

Group By

Select
     (MONTHS - (MONTHS % 10)) As RANGE
   , Count(CUST)              As CUST_COUNT,
   , Count(CATEGORY)          As CATEGORY_COUNT
From
     tbale --< :-)
Group By
     (MONTHS - (MONTHS % 10)); --< Expression that would result in the same value for the entire RANGE

答案 2 :(得分:1)

Giorgos Betsos&#39;答案调整为使用派生表。无需两次输入CASE表达式。符合ANSI SQL(因为GROUP BY子句中只允许列。)

select MONTHS, COUNT(CUST) AS CUST_COUNT, COUNT(CATEGORY) AS CATEGORY_COUNT
from
(
    SELECT CASE 
                WHEN MONTHS BETWEEN 10 AND 19 THEN '10-19'
                WHEN MONTHS BETWEEN 20 AND 29 THEN '20-29'
                WHEN MONTHS BETWEEN 30 AND 39 THEN '30-39'
                WHEN MONTHS BETWEEN 40 AND 49 THEN '40-49'
                ELSE '50-'
             END AS MONTHS,
         CUST,
         CATEGORY
    FROM mytable
)
GROUP BY MONTHS