在SQL中将数字拆分为范围

时间:2019-05-24 07:04:15

标签: sql sql-server range

我正在尝试编写一个SQL查询,以显示自2015年1月31日以来客户资历的分布:

  1. 长达一个月
  2. 一到六个月
  3. 六个月至一年之间
  4. 一年以上

我成功地将客户的月数进行了分组和分组。

SELECT Seniority, COUNT(Customer_ID) [Number of Customers]
FROM
(SELECT Customer_ID,
DATEDIFF(MONTH, MIN(CONVERT(datetime, Order_Date)), '2015/01/31') Seniority
FROM Orders
GROUP BY Customer_ID) t
GROUP BY Seniority

enter image description here

如何按给定范围划分?

预期:

        Seniorty                |   Number of Customers
Up to one month                 |            0
Between one and six months      |            14
Between six months and one year |            1
Over a year                     |            0

2 个答案:

答案 0 :(得分:2)

使用条件聚合:

WITH cte AS (
    SELECT
        'Up to one month' AS Seniority,
        COUNT(CASE WHEN DATEDIFF(MONTH, Order_Date, '2015-01-31') < 1 THEN 1 END) AS [Number of Customers],
        1 AS position
    FROM Orders
    UNION ALL
    SELECT
        'Between one and six months',
        COUNT(CASE WHEN DATEDIFF(MONTH, Order_Date, '2015-01-31') >= 1 AND
                        DATEDIFF(MONTH, Order_Date, '2015-01-31') < 6 THEN 1 END),
        2
    FROM Orders
    UNION ALL
    SELECT
        'Between six months and one year',
         COUNT( CASE WHEN DATEDIFF(MONTH, Order_Date, '2015-01-31') >= 6 AND
                        DATEDIFF(MONTH, Order_Date, '2015-01-31') < 12 THEN 1 END),
         3
    FROM Orders
    UNION ALL
    SELECT
        'Over a year',
        COUNT(CASE WHEN DATEDIFF(MONTH, Order_Date, '2015-01-31') > 12 THEN 1 END),
        4
    FROM Orders
)

SELECT
    Seniority,
    [Number of Customers]
FROM cte
ORDER BY
    position;

此答案假定Order_Date列已经是日期或日期时间。如果没有,那么您应该做的第一件事就是将该列转换为实际的日期类型。

答案 1 :(得分:1)

WITH CTE AS (
    SELECT CUSTOMER_ID,
           CASE WHEN DATEDIFF(MONTH,'2015-01-31',ORDER_DATE)=1 THEN 'Up to one month'
               WHEN DATEDIFF(MONTH,'2015-01-31',ORDER_DATE) BETWEEN 1 AND 6 THEN 'Between one and six months'
               WHEN DATEDIFF(MONTH,'2015-01-31',ORDER_DATE) BETWEEN 6 AND 12 THEN 'Between six months and one year'
               WHEN DATEDIFF(MONTH,'2015-01-31',ORDER_DATE)>12 THEN 'Over a year'
           END AS SENIORITY
      FROM ORDERS 
     )
SELECT SENIORITY AS 'Seniority', COUNT(CUSTOMER_ID) AS 'Number of Customers'
FROM CTE
WHERE SENIORITY IS NOT NULL
GROUP BY SENIORITY