查询数据库显示上午和下午完成的记录数

时间:2013-05-14 05:11:06

标签: mysql

我有一个简单的表(walkin2012),其中包含以下字段:

ID |    date    |    store   | timestamp            | custName
1  | 2013-05-08 | Plainfield | 2013-05-08 10:38:40  | cust1
2  | 2013-05-08 | Plainfield | 2013-05-08 13:38:40  | cust2
3  | 2013-05-09 | Bayport    | 2013-05-09 20:38:40  | cust3
4  | 2013-05-10 | Plainfield | 2013-05-10 17:38:40  | cust4
5  | 2013-05-10 | Bayport    | 2013-05-10 11:38:40  | cust4

我想查询表格,以显示上午10点至下午1点之间完成的记录数量,以及每个商店每个日期下午后的任何内容,以便它只是给我这个结果:

date       | store      | morning | afternoon
2013-05-08 | Plainfield | 1       | 1
2013-05-09 | Bayport    | 0       | 1
2013-05-10 | Bayport    | 1       | 0
2013-05-10 | Plainfield | 0       | 1

我得到了约会,商店和上午的工作,但我对如何在下午部分进行子查询感到困惑。这是我到目前为止的查询:

SELECT date, store, count(walkinID) AS Morning 
FROM walkin2012 
WHERE timestamp
BETWEEN concat_ws(' ',date,'10:00:00') AND concat_ws(' ',date,'13:00:00')  
GROUP BY date,store

任何帮助将不胜感激。非常感谢你。

2 个答案:

答案 0 :(得分:4)

SELECT  date, 
        store, 
        SUM(timestamp BETWEEN date + interval 10 hour AND 
                              date + interval 13 hour) Morning,
        SUM(timestamp BETWEEN date + interval 13 hour AND 
                              date + interval 24 hour) Afternoon
FROM    walkin2012   
GROUP   BY date, store

答案 1 :(得分:0)

你可以试试这个

SELECT a.date, a.store, sum(Morning) as Morning, sum(afternoon) as afternoon FROM (
  SELECT date, store, count(walkinID) AS Morning , 0 AS Afternoon
  FROM walkin2012 
  WHERE timestamp
  BETWEEN concat_ws(' ',date,'10:00:00') AND concat_ws(' ',date,'13:00:00')  
  GROUP BY date,store
  UNION
  SELECT date, store, 0 AS Morning, count(walkinID) AS Afternoon
  FROM walkin2012 
  WHERE timestamp
  < concat_ws(' ',date,'10:00:00') OR timestamp > concat_ws(' ',date,'13:00:00')  
  GROUP BY date,store
) a
GROUP BY a.date, a.store