1

我正在尝试查询以 30 分钟间隔对客户记录进行分组,同时汇总 30 分钟间隔内的客户数量和每个客户花费的总金额。

我是新来的,我正在努力解决这个问题。

我正在使用 Microsoft SQL 2005。

这是我的主表的示例:

Cust_ID (Prime key), Date_time (Time of order), Price, and Sales_Tax

间隔应该在特定日期0-2930-59每小时之间。

我已经想出了如何简单地按日期范围选择记录。但我无法使用分组功能。

4

1 回答 1

1
    SELECT SUM(price)            AS price_sum,
       SUM(tax)                  AS tax_sum,
       COUNT(DISTINCT cust_id)   AS cust_count,
       CONVERT(varchar(13), time_of_order, 120) 
        + CASE 
             WHEN DATEPART(minute, time_of_order) < 30 THEN 'A'
             ELSE 'B'
          END           AS time_chunk_hash
  FROM Sales
       GROUP BY CONVERT(varchar(13), time_of_order, 120) 
                    + CASE 
                         WHEN DATEPART(minute, time_of_order) < 30 THEN 'A'
                         ELSE 'B'
                      END
       ORDER BY CONVERT(varchar(13), time_of_order, 120)  
                  +  CASE 
                        WHEN DATEPART(minute, time_of_order) < 30 THEN 'A'
                        ELSE 'B'
                     END

一个工作示例位于:http ://sqlfiddle.com/#!3/794ae/12

计算time_chunk_hash用于对输出进行排序和分组,如下所示:

 2013-07-28 15A
 2013-07-29 15B

例如,这将指示 7 月 28 日下午 3 点之后的前半小时,然后是后半小时。

这是呈现相同查询的更易读的方式

SELECT SUM(price)                  AS price_sum,
       SUM(tax)                    AS tax_sum,
       COUNT(DISTINCT cust_id)     AS cust_cnt,
       time_chunk_hash
   FROM 
   (
      SELECT price,
             tax,
             cust_id,
             CONVERT(varchar(13), time_of_order, 120)
              + CASE 
                   WHEN DATEPART(minute, time_of_order) < 30 THEN 'A'
                   ELSE 'B'
               END           AS time_chunk_hash
        FROM Sales
   ) HASHED
     GROUP BY time_chunk_hash
     ORDER BY time_chunk_hash

一个工作示例位于: http ://sqlfiddle.com/#!3/794ae/11

于 2013-07-29T01:58:55.403 回答