22,209
社区成员
发帖
与我相关
我的任务
分享
--测试数据
if not object_id(N'Tempdb..#A') is null
drop table #A
Go
Create table #A([id] int,[address] nvarchar(22),[level] nvarchar(23))
Insert #A
select 2,N'北京',N'I' union all
select 3,N'上海',N'II' union all
select 5,N'广东',N'III' union all
select 6,N'北京',N'I' union all
select 7,N'上海',N'III'
Go
--测试数据结束
SELECT ADDRESS,
ISNULL(I, 0) AS I,
ISNULL(II, 0) AS II,
ISNULL(III, 0) AS III
FROM (
SELECT ADDRESS,
LEVEL,
1 AS c
FROM #A AS a
) AS a1 PIVOT(SUM(c) FOR LEVEL IN (I, II, III)) AS p
--测试数据
if not object_id(N'Tempdb..#A') is null
drop table #A
Go
Create table #A([id] int,[address] nvarchar(22),[level] nvarchar(23))
Insert #A
select 2,N'北京',N'I' union all
select 3,N'上海',N'II' union all
select 5,N'广东',N'III' union all
select 6,N'北京',N'I' union all
select 7,N'上海',N'III'
Go
--测试数据结束
declare @sql varchar(8000)
set @sql='select [address] '
select @sql=@sql+' , sum(case [level] when '''+ [level] +''' then 1 else 0 end) [水质'+ [level] +'总数]'
from (SELECT DISTINCT [level] FROM #A)a
set @sql=@sql+' from #A group by [address]'
EXEC(@sql)
--测试数据
if not object_id(N'Tempdb..#A') is null
drop table #A
Go
Create table #A([id] int,[address] nvarchar(22),[level] nvarchar(23))
Insert #A
select 2,N'北京',N'I' union all
select 3,N'上海',N'II' union all
select 5,N'广东',N'III' union all
select 6,N'北京',N'I' union all
select 7,N'上海',N'III'
Go
--测试数据结束
declare @sql varchar(8000)
set @sql='select [address] '
select @sql=@sql+' , sum(case [level] when '''+ [level] +''' then 1 else 0 end) [水质'+ [level] +'总数]'
from #A
set @sql=@sql+' from #A group by [address]'
EXEC(@sql)