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