日期:2014-05-17  浏览次数:20574 次

请教关于count(*)与like的查询语句
select 
(select count(*) 
from cpl_OrderItems 
where day= '2013-08-01' and businesstypename like 'aaa%') as '1',
(select count(*) 
from cpl_OrderItems 
where day= '2013-08-02' and businesstypename like 'aaa%') as '2',
。。。。。。
(select count(*) 
from cpl_OrderItems 
where day= '2013-08-31' and businesstypename like 'aaa%') as '31'

该语句的查询结果只有一条记录共31个字段,为1-31号businesstypename字段以aaa开头的每天的记录数。这条语句只能查询以aaa开头的记录数,现在我想通过一条语句分别查询aaa开头的每天的记录数和bbb开头的每天的记录数,即查询结果有2条记录,该怎么写?请各位大侠指点!但愿我说明白了。。。。


sql? count(*) like

------解决方案--------------------
select day,count(*) 
from cpl_OrderItems 
where  businesstypename like 'aaa%' or businesstypename like 'bbb%' 
group by day

这样?
------解决方案--------------------
应该改为sum才对:
select left(businesstypename,3) as businesstypename
,[1]=sum(case when datepart(day,[day])=1 then 1 else 0 end)
,[2]=sum(case when datepart(day,[day])=2 then 1 else 0 end)
,[3]=sum(case when datepart(day,[day])=3 then 1 else 0 end)
.....................
.......
,[31]=sum(case when datepart(day,[day])=31 then 1 else 0 end)
from cpl_OrderItems
where convert(varchar(7),[day],120)='2013-07' and (businesstypename like 'aaa%' or businesstypename like 'bbb%')
group by left(businesstypename,3)



------解决方案--------------------
呵呵,简单的办法:

select 
(select count(*) 
from cpl_OrderItems 
where day= '2013-08-01' and businesstypename like 'aaa%') as '1',
(select count(*) 
from cpl_OrderItems 
where day= '2013-08-02' and businesstypename like 'aaa%') as '2',
。。。。。。
(select count(*) 
from cpl_OrderItems 
where day= '2013-08-31' and businesstypename like 'aaa%') as '31'

union all

select 
(select count(*) 
from cpl_OrderItems 
where day= '2013-08-01' and businesstypename like 'bbb%') as '1',
(select count(*) 
from cpl_OrderItems 
where day= '2013-08-02' and businesstypename like 'bbb%') as '2',
。。。。。。
(select count(*) 
from cpl_OrderItems 
where day= '2013-08-31' and businesstypename like 'bbb%') as '31'


------解决方案--------------------
引用:<