Inner Join Pivot SQL

时间:2012-07-05 14:59:56

标签: sql sql-server-2008

我有2个表,tblClient和tblDB。

CREATE TABLE tblBD(
[ID] INT PRIMARY KEY,
[DataBase] nVARCHAR (30) NOT NULL,
[ClientID] INT NOT NULL,
FOREIGN KEY ([ClientID]) REFERENCES tblClient(ID)
)

CREATE TABLE tblClient(
[ID] INT PRIMARY KEY,
[Name] nVARCHAR(30),
[Status] BIT,
[Number] INT,
)

我想要一种方法来为每个客户提供他所有的数据库。

这样的事情:

Client1 Client2 ClientX
BD1     BD1     BD1 
BD2     BD2     BD2
BDX     BDX     BDX

我可以通过执行此脚本轻松地为一个客户端执行此操作:

Select tblBD.[DataBase] from tblBD
inner join tblCLient on tblBD.ClientID = tblClient.ID Where tblClient.ID = 1234

但是,我无法想象如何在1个表中获得所有客户的结果。

对于枢轴我没有使用聚合函数就无法得到结果。

示例:

WITH T
AS (Select tblBD.[DataBase] as BD, tblClient.ID as ClientID from
tblBD inner join tblCLient on tblBD.ClientID = tblClient.ID)
SELECT *
FROM   T PIVOT ( 
max (BD) FOR ClientID IN ([1],[2],[3], [4])
) AS pvt

我想在不使用聚合函数的情况下获取所有数据库。

1 个答案:

答案 0 :(得分:1)

首先,我从中得到了启发:

http://www.sqlmag.com/article/tsql3/pivoting-without-aggregation

执行此脚本以获取客户端数量:

SELECT COUNT( DISTINCT tblBD.ClientID) FROM tblBD

根据需要创建尽可能多的客户。

有4个客户的示例,在我的情况下:

SELECT [1] AS Client1, [2] AS Client2, [3] AS Client3, [4] AS Client4
FROM
(
    Select tblBD.[DataBase] AS BD,
    tblBD.ClientID AS ClientID ,
    ROW_NUMBER() OVER (PARTITION BY ClientID ORDER BY ClientID) AS RowNum 
    FROM tblBD
) Piv
PIVOT (MAX(BD) FOR ClientID IN ([1],[2],[3], [4])) AS pvt 

您可以在代码中构建一个查询字符串,其中包含任意数量的客户端。