sql多表行转列、级联行转列示例代码
程序员文章站
2024-02-05 23:04:22
现有两表a,b a表存储商品点击日志,b表存储商品 要求显示当天所有商品点击量列表并附带总数并按天排序 复制代码 代码如下: declare @sql varchar(20...
现有两表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)
显示结果
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 |
下一篇: sql使用cast进行数据类型转换示例