現有兩表A,B
A表存儲商品點擊日志,B表存儲商品
要求顯示當天所有商品點擊量列表並附帶總數並按天排序
復制代碼 代碼如下:
declare @sql varchar(2000)
set @sql='select CONVERT(varchar(100), a.[Time], 23) as 時間,count(b.title) as 總數'
select @sql =@sql+ ',sum(case b.title when '''+Title+''' then 1 else 0 end) as '+'['+Title+']'
from (select distinct title from B) as B
set @sql=@sql+' from A as a left join B as b on a.AId=B.Aid
group by CONVERT(varchar(100), a.[Time], 23) order by CONVERT(varchar(100), a.[Time], 23) desc'
exec(@sql)
顯示結果
時間
總數
商品1
商品2
商品3
2013-11-11
5
1
0
4
2013-11-10
13
2
11
1