求一条复杂的sql语句(也可以通过其它方式实现这个功能、比如用N条sql语句进行查询得到结果最后整合)
原始表中有时间列(dataTime)、名字列(nvchar)、是否本地(bit/bool) 这三个列。
我想通过一条sql语句,统计出 “每个名字、每一天 的本地数量 和非本地数量。”
这样说您可能有些糊涂。举个例子,就像如下两个表,我的目标是将原始数据表中的信息统计为目标表那个样子。
原始数据表
时间 名字 是否本地今天上午 张三 true 今天下午 张三 false 昨天上午 张三 true 昨天下午 张三 true 前天上午 张三 false 前天中午 张三 true 前天下午 张三 false 今天上午 李四 true 今天中午 李四 false今天下午 李四 false 昨天上午 李四 false 昨天中午 李四 true昨天下午 李四 true 前天上午 李四 false 前天中午 李四 true 前天下午 李四 false
时间 名字 本地数量 非本地数量 咨询总数今天 张三 1 1 2昨天 张三 2 0 2前天 张三 1 2 3今天 李四 1 2 3昨天 李四 2 1 3前天 李四 1 2 3
select convert(varchar(10),时间,120),名字, 本地数量=sum(case when 是否本地='true' then 1 else 0 end), 非本地数量=sum(case when 是否本地='false' then 1 else 0 end), 咨询总数=count(*)from tb group by convert(varchar(10),时间,120),名字order by 名字,convert(varchar(10),时间,120) desc
[解决办法]
select convert(varchar(10),时间,120),名字, sum(case when 是否本地='true' then 1 else 0 end) as 本地数量, sum(case when 是否本地='false' then 1 else 0 end) as 非本地数量, count(1) as 咨询总数from tb group by convert(varchar(10),时间,120),名字order by 名字,convert(varchar(10),时间,120) desc
[解决办法]
SELECT CONVERT(VARCHAR(10),时间列,120) AS 日期,名字,SUM(是否本地*1) AS 本地数量,SUM(1-是否本地*1) AS 非本地数量,COUNT(1) AS 咨询总数FROM table1 WHERE DATEDIFF(d,时间列,GETDATE())<=2GROUP BY CONVERT(VARCHAR(10),时间列,120)ORDER BY 名字,日期
[解决办法]
create table tb(时间 datetime,名字 nvarchar(10),是否本地 bit)insert into tb select '2011-12-07 01:30','张三',1 insert into tb select '2011-12-07 21:30','张三',0insert into tb select '2011-12-06 01:30','张三',1 insert into tb select '2011-12-06 21:30','张三',1 insert into tb select '2011-12-05 21:30','张三',0insert into tb select '2011-12-05 21:30','张三',1 insert into tb select '2011-12-05 21:30','张三',0insert into tb select '2011-12-07 21:30','李四',1 insert into tb select '2011-12-07 21:30','李四',0insert into tb select '2011-12-06 21:30','李四',0 insert into tb select '2011-12-06 21:30','李四',0insert into tb select '2011-12-06 21:30','李四',1insert into tb select '2011-12-05 21:30','李四',1 insert into tb select '2011-12-05 21:30','李四',0insert into tb select '2011-12-05 21:30','李四',1insert into tb select '2011-12-05 21:30','李四',0goselect convert(varchar(10),时间,120)时间,名字,sum(case when 是否本地=1 then 1 else 0 end)本地数量,sum(case when 是否本地=1 then 0 else 1 end)非本地数量,count(*)咨询总数from tb group by convert(varchar(10),时间,120),名字order by 名字,1 desc/*时间 名字 本地数量 非本地数量 咨询总数---------- ---------- ----------- ----------- -----------2011-12-07 李四 1 1 22011-12-06 李四 1 2 32011-12-05 李四 2 2 42011-12-07 张三 1 1 22011-12-06 张三 2 0 22011-12-05 张三 1 2 3(6 行受影响)*/godrop table tb
[解决办法]
select convert(varchar(10),时间,120)时间,名字,sum(case when 是否本地=1 then 1 else 0 end)本地数量,sum(case when 是否本地=1 then 0 else 1 end)非本地数量,count(*)咨询总数from tb group by convert(varchar(10),时间,120),名字order by 名字,1 desc
[解决办法]
select
convert(varchar(10),时间,120),名字,
sum(case when 是否本地='true' then 1 else 0 end) as 本地数量,
sum(case when 是否本地='false' then 1 else 0 end) as 非本地数量,
count(*) as 咨询总数
from
tb
group by
convert(varchar(10),时间,120),名字
order by
名字,convert(varchar(10),时间,120) desc