需要计数查询

时间:2013-12-24 17:01:58

标签: sql sql-server-2008 date datetime time

ID          Time                    Status
----------- ----------------------- --------------------------------------------------
1           2013-12-24 00:00:00     on
2           2013-12-25 00:00:00     on
3           2013-12-26 00:00:00     on
4           2013-12-27 00:00:00     on
5           2013-12-28 00:00:00     on
6           2013-12-29 00:00:00     on
7           2013-12-30 00:00:00     on
8           2013-12-31 00:00:00     on
9           2013-12-24 00:00:00     off
10          2013-12-25 00:00:00     off
11          2013-12-27 00:00:00     off
12          2013-12-27 00:00:00     on
13          2013-12-27 00:00:00     off
14          2013-12-27 00:00:00     on
15          2013-12-27 00:00:00     off
16          2013-12-28 00:00:00     on
17          2013-12-28 00:00:00     off
18          2013-12-28 00:00:00     on
19          2013-12-29 00:00:00     off
20          2013-12-29 00:00:00     on
21          2013-12-30 00:00:00     off
22          2013-12-30 00:00:00     on
23          2013-12-30 00:00:00     off
24          2013-12-30 00:00:00     on
25          2013-12-30 00:00:00     off
26          2013-12-31 00:00:00     on
27          2013-12-31 00:00:00     off
28          2013-12-31 00:00:00     on
29          2013-12-31 00:00:00     off
30          2013-12-31 00:00:00     on
31          2013-12-31 00:00:00     off

我有这个数据,我想要一个按日期和开关分类的查询

列名为Date,On,Off,我正在使用Microsoft SQL Server 2008

3 个答案:

答案 0 :(得分:1)

让我们说包含日期的列名为yourDateColumn,包含状态的列名为statusColumn,您可以这样做:

SELECT yourDateColumn, 
 SUM(statusColumn="On") as On, 
 SUM(statusColumn="Off") as Off 
 FROM yourTable 
 GROUP BY yourDateColumn
 ORDER BY yourDateColumn

答案 1 :(得分:0)

我不知道你的桌子的名称或结构是什么,但从我能够弄清楚它的数据应该有效。

SELECT Date, SUM(status="On") as On_count, SUM(status="Off") as Off_count 
FROM Table 
GROUP BY Date 
Order by Date;

答案 2 :(得分:0)

SELECT t.Time, Count(t_on.id),Count(t_off.id) FROM Table1 t
LEFT JOIN Table1 t_on
ON t.id= t_on.id and t_on.Status = 'on'
LEFT JOIN Table1 t_off
ON t.id= t_off.id and t_off.Status = 'off'
GROUP BY t.Time Order by Time;

<强> Fiddle