首页 > 数据库 > SQL Server > 正文

sql多表行转列、级联行转列示例代码

2020-07-25 12:59:33
字体:
来源:转载
供稿:网友
现有两表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-115104
2013-11-10132111
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表