按日期条件获取分组数据

时间:2014-10-07 12:00:52

标签: sql sqlite

我有一个具有以下结构的表:

enter image description here

我想创建一个查询,它给出了两个日期范围的以下格式的结果:

    FROM       |   TO       |    DIALS_CNT   | APPT_CNT | CONVERS_CNT | CANNOT_REACH_CNT | 
    2014-09-30 |  2014-10-06|    100         | 50       | 20          |  30            |
    FROM = Date from given to between range
    TO = Date to given to between range
    APPT_CNT = WHERE call.result = APPT
    CONVERS_CNT = WHERE call.result = CONV_NO_APPT
    CANNOT_REACH_CNT = WHERE call.result = CANNOT_REACH

我尝试使用带有count和WHERE条件的内部选择,但没有运气:

SELECT 
  dc.date,
  (SELECT COUNT('APPT') FROM dialed_calls 
  WHERE dc.call_result = 'APPT') as APPT_CNT
FROM dialed_calls AS dc
GROUP BY dc.date  
WHERE dc.date BETWEEN '2014-09-30' AND '2014-10-06';

3 个答案:

答案 0 :(得分:1)

你的问题真的不清楚。根据你的代码,我猜你有一个带有call_result列和日期列的调用详细信息表。

如果你想通过call_result计算不同类型的调用,你可以使用sum而不是像这样计算:

SELECT '2014-09-30' as from,
       '2014-10-06' as to,
       COUNT(*) AS DIALS_CNT,   
       SUM(CASE WHEN dc.call_result = 'APPT' THEN 1 ELSE 0 END) AS APPT_CNT,
       SUM(CASE WHEN dc.call_result = 'CONV_NO_APPT' THEN 1 ELSE 0 END) AS CONVERS_CNT ,
       SUM(CASE WHEN dc.call_result = 'CANNOT_REACH' THEN 1 ELSE 0 END) AS CANNOT_REACH_CNT 
  FROM dialed_calls dc
 WHERE  dc.date BETWEEN '2014-09-30' AND '2014-10-06'

答案 1 :(得分:0)

您要查找的是BETWEEN语句以获取相应的日期范围,并使用COUNT聚合来列出您的计数。 Here是SQLite的有用运算符列表,here是有关聚合的一些详细信息。

请谨慎列出您的日期范围,如question所示,SQLite对它的日期格式很挑剔。

<强> ---------------------------------- EDIT --------- --------------------------

尝试此查询:

SELECT dc.date, COUNT('APPT')
FROM dialed_calls AS dc
WHERE dc.date BETWEEN '2014-09-30' AND '2014-10-06'
GROUP BY dc.date;

答案 2 :(得分:0)

这就像your earlier question,但有两列和BETWEEN:

SELECT zFrom AS "FROM",
       zTo AS "TO",
       (SELECT COUNT(*)
        FROM MyTable
        WHERE date BETWEEN zFrom AND zTo
       ) AS Dials_Cnt,
       (SELECT SUM(Call_Result = 'APPT')
        FROM MyTable
        WHERE date BETWEEN zFrom AND zTo
       ) AS Appt_Cnt,
       ...
FROM (SELECT '2014-09-30' AS zFrom, '2014-10-06 9' AS zTo UNION ALL
      SELECT '2014-10-07',          '2014-10-13 9'        UNION ALL
      ...)

结束日期中的额外9可确保时间与该日期相匹配。