我有一个名为Call_Data的表,数据如下:
Arr_Date Interval AN_Time AB_Time
08/08/2011 1600 113 NULL
08/08/2011 1400 317 NULL
08/09/2011 1200 298 NULL
08/09/2011 1000 NULL 194
08/10/2011 1200 256 NULL
08/10/2011 1400 NULL 132
我希望输出如下:
Arr_Date Total_calls AN_10_min AN_5_min AB_10_Min AB_5_min
08/08/2011 2 2 1 0 0
08/09/2011 2 1 1 1 1
08/10/2011 2 1 1 1 1
逻辑是列AN_Time,AB_Time以秒为单位。我想计算每列10分钟和5分钟范围内每天的通话次数。
我写了这样的话:
SELECT ARR_date,
CASE WHEN AN_TIME <300 THEN 1 ELSE 0 END AS AN_5_min ,
case WHEN AN_TIME <600 THEN 1 ELSE 0 END AS AN_10_min,
CASE WHEN AB_TIME <300 THEN 1 ELSE 0 END AS AB_5_min ,
case WHEN AB_TIME <600 THEN 1 ELSE 0 END AS AB_10_min
FROM Call_Data
GROUP BY AR_Date,AN_TIME,AB_TIME
但这并没有给我带来总呼叫次数。任何人都可以帮助我吗?
答案 0 :(得分:3)
你很亲密:
SELECT
ARR_date,
COUNT(*) AS Total_calls,
SUM( CASE WHEN AN_TIME <300 THEN 1 ELSE 0 END ) AS AN_5_min ,
SUM( CASE WHEN AN_TIME <600 THEN 1 ELSE 0 END ) AS AN_10_min,
SUM( CASE WHEN AB_TIME <300 THEN 1 ELSE 0 END ) AS AB_5_min ,
SUM( CASE WHEN AB_TIME <600 THEN 1 ELSE 0 END ) AS AB_10_min
FROM Call_Data
GROUP BY AR_Date
您还可以使用NULL
和COUNT
向任何未来的编码人员展示您实际上正在计算通话数而不是总结:
SELECT
ARR_date,
COUNT(*) AS Total_calls,
COUNT( CASE WHEN AN_TIME <300 THEN 1 ELSE NULL END ) AS AN_5_min ,
COUNT( CASE WHEN AN_TIME <600 THEN 1 ELSE NULL END ) AS AN_10_min,
COUNT( CASE WHEN AB_TIME <300 THEN 1 ELSE NULL END ) AS AB_5_min ,
COUNT( CASE WHEN AB_TIME <600 THEN 1 ELSE NULL END ) AS AB_10_min
FROM Call_Data
GROUP BY AR_Date
答案 1 :(得分:2)
你几乎就在那里,只需将列加起来
SELECT
ARR_date,
SUM(AN_5_min) AN_5_min,
SUM(AN_10_min) AN_10_min,
SUM(AB_5_min) AB_5_min,
SUM(AB_10_min) AB_10_min
FROM
(SELECT
ARR_date,
CASE WHEN AN_TIME <300 THEN 1 ELSE 0 END AS AN_5_min,
case WHEN AN_TIME <600 THEN 1 ELSE 0 END AS AN_10_min,
CASE WHEN AB_TIME <300 THEN 1 ELSE 0 END AS AB_5_min,
case WHEN AB_TIME <600 THEN 1 ELSE 0 END AS AB_10_min
FROM
Call_Data) TBL
GROUP BY
ARR_date
答案 2 :(得分:1)
SELECT Arr_Date, COUNT(*) AS Total_Calls,
SUM(CASE WHEN AN_TIME <300 THEN 1 ELSE 0 END) AS AN_5_min ,
SUM(case WHEN AN_TIME <600 THEN 1 ELSE 0 END) AS AN_10_min,
SUM(CASE WHEN AB_TIME <300 THEN 1 ELSE 0 END) AS AB_5_min ,
SUM(case WHEN AB_TIME <600 THEN 1 ELSE 0 END) AS AB_10_min
FROM dbo.Call_Data
GROUP BY Arr_Date
ORDER BY Arr_Date;