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'
------解决方案--------------------
不会,他的写法是非常好的写法,优化了你原来的写法,不仅没有加大压力,应该说是减轻了你的服务器压力。