Sql server SQL联合或水平联合

Sql server SQL联合或水平联合,sql-server,join,count,union,Sql Server,Join,Count,Union,我试图将下面的查询放在查询的一行中。下面只是一个例子,我有大约10个计数合并成一行 select ISNULL(COUNT(*),0) as ENGLAND from Service_User s where s.commissioner_id ='1' select ISNULL(COUNT(*),0) as WALES from Service_User s where s.commissioner_id ='2' select ISNULL(COUNT(*),0) as GERMA

我试图将下面的查询放在查询的一行中。下面只是一个例子,我有大约10个计数合并成一行

select ISNULL(COUNT(*),0) as ENGLAND from Service_User s 
where s.commissioner_id ='1'

select ISNULL(COUNT(*),0) as WALES from Service_User s 
where s.commissioner_id ='2'

select ISNULL(COUNT(*),0) as GERMANY from Service_User s 
where s.commissioner_id ='3'
我曾尝试将它们合并,但它们是垂直显示的,我希望它们是水平显示的

我希望它看起来像下面这样


试试这个。使用
子选择

SELECT (SELECT Isnull(Count(*), 0)
        FROM   Service_User s
        WHERE  s.commissioner_id = '1') AS ENGLAND,
       (SELECT Isnull(Count(*), 0)
        FROM   Service_User s
        WHERE  s.commissioner_id = '2') AS WALES,
       (SELECT Isnull(Count(*), 0)
        FROM   Service_User s
        WHERE  s.commissioner_id = '3') AS GERMANY 

如果您使用的是Sql Server 2012或更高版本,那么它可以更短

试试这个

;With CTE As

(
select commissioner_id, ROW_NUMBER()Over(Partition By commissioner_id order by commissioner_id) RowNum  from Service_User s 
 s.commissioner_id  in(1,2,3)

)
,CTE1 as
(
 Select commissioner_id,MAX(RowNum) from CTE
 group By commissioner_id
)

select * from CTE
--pivot this result set

如果我知道我的专员id并没有改变,我可以将这些值加载到查询中,我将使用选项1

SELECT * FROM (select COUNT(*) As Count,(select case commissioner_id when '01' then 'England' when '02' then 'Wales' when '03' then 'Germany' else 'Other') as [Location] from Service_User group by [Location]) as s PIVOT (SUM(count) FOR [Location] IN ("England","Wales","Germany","Other")) AS PivotOut
第二个选项我将创建一个存储过程,动态加载commissioner_id的选项,然后进行数据透视。通过这种方式,添加专员ID时,无需手动干预即可返回所需结果

Create PROCEDURE [dbo].[DynamicSP]
AS
BEGIN
    declare @sql as varchar(max)
    declare @dynamic varchar(max)

    select @dynamic=COALESCE(@dynamic +',','')+commissioner_id
    FROM 
    (select distinct commissioner_id from Service_User) as CommIds order by commissioner_id

    set @SQL = '(select COUNT(*) As count,commissioner_id as [Location] from Service_User group by [Location]) as s PIVOT (SUM(count) FOR [Location] IN (' + @dynamic + ')) AS PivotOut'

    exec(@sql)
END

谢谢,我想这项工作已经完成了。这个查询速度会慢很多。你不必使用
ISNULL(COUNT(*),0)
just
COUNT(*)
如果没有找到任何记录,将返回0。。。