0

我有 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

但是,我不知道如何在一张表中获得所有客户的结果。

对于枢轴,如果不使用聚合函数,我将无法获得结果。

例子 :

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

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

4

1 回答 1

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 

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

于 2012-07-06T12:20:43.760 回答