0

我有一张桌子,我需要自己加入并找到丢失的物品,但我被卡住了。也许这只是一个经验不足的问题,但我似乎只能用循环来完成我想要的。

基本上该表如下:

    packageID     Server
      1           baseline
      2           baseline
      3           baseline
      1           server1
      3           server1
      2           server2
      3           server2

我希望完成的是找出每台服务器缺少哪些包。我可以在服务器的基础上得到这个,如下所示:

    SELECT base.*, ISNULL(dp.server,'server1') as Server
    FROM (SELECT DISTINCT packageID FROM DB1
          WHERE server = 'baseline') base
    LEFT OUTER JOIN 
         (SELECT packageID, server FROM DB1
          WHERE server = 'server1') dp
   WHERE dp.server IS NULL

这在单个服务器的基础上为我提供了我想要的东西。

    packageID     Server
       2          server1 

我将如何完成获取基线中缺少特定服务器的每个包的列表?

4

2 回答 2

1

假设一个带有服务器列表的视图,并将其视为伪 SQL,因为我无法对其进行测试,我认为这样的事情应该可以工作......

SELECT base.packageID, servers.server, 
             (SELECT count(*) 
                FROM base AS b1
               WHERE b1.packageId = base.packageId
                 AND b1.server    = servers.server) deployed
  FROM base, servers
 WHERE base.server = 'baseline'
   AND deployed = 0;
于 2013-03-15T11:31:55.667 回答
0

试试这个脚本,

      DECLARE @DB1 TABLE
(
    PackageID INT
    ,Server VARCHAR(50)
)


INSERT INTO @DB1 VALUES(1,'baseline')
INSERT INTO @DB1 VALUES(2,'baseline')
INSERT INTO @DB1 VALUES(3,'baseline')
INSERT INTO @DB1 VALUES(1,'server1')
INSERT INTO @DB1 VALUES(3,'server1')
INSERT INTO @DB1 VALUES(2,'server2')
INSERT INTO @DB1 VALUES(3,'server2')

;WITH CTE_Package AS
(
    SELECT DISTINCT PackageID 
        , ROW_NUMBER() OVER(order by PackageID) AS ID
    FROM @DB1
)
,CTE_Servers AS
(
    SELECT DISTINCT Server 
        , ROW_NUMBER() OVER(order by PackageID) AS ID
    FROM @DB1
)
,CTE_Server_Packages AS
(
    SELECT DISTINCT P.PackageId, S.Server   
    FROM CTE_Servers S
    CROSS JOIN CTE_Package P    
)
SELECT Server, PackageID
FROM 
(
    SELECT SP.Server, SP.PackageID , D.PackageID [ActualPackage], D.Server [ActualServer]
    FROM CTE_Server_Packages SP
    LEFT JOIN @DB1 D
            ON D.PackageID = SP.PackageID
            AND D.Server = SP.Server
) AS TEMP
WHERE TEMP.ActualServer IS NULL
于 2013-03-15T11:56:37.633 回答