sql多表行轉(zhuǎn)列/級聯(lián)行轉(zhuǎn)列示例代碼

字號:


    現(xiàn)有兩表A,B
    A表存儲商品點擊日志,B表存儲商品
    要求顯示當天所有商品點擊量列表并附帶總數(shù)并按天排序
    代碼如下:
    declare @sql varchar(2000)
    set @sql='select CONVERT(varchar(100), a.[Time], 23) as 時間,count(b.title) as 總數(shù)'
    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)
    顯示結(jié)果
    
1.jpg