带有JOIN的3个表上的SQL COUNT

时间:2017-08-11 15:03:16

标签: sql-server database join sum

我在数据库中有4个表。仓库包含客户拥有的箱子,箱子中有文件。有Client表,Warehouse表,Boxes表和Files表。

因此Client表有WarehouseID作为外键,Boxes表有ClientID作为外键,Files表有{ {1}}作为外键。我想计算每个客户在查询中包含的方框和文件的数量,以及进出仓库的方框数。 BoxIDStatus表上的Boxes字段确定框和文件是否在仓库内或外。我在框上运行以下查询,数字是正确的:

Files

这会产生以下输出:

SELECT
    [c].[ClientID],
    [c].[Name] AS [ClientName],
    [w].[Name] AS [WarehouseName],
    COUNT(DISTINCT [b].[BoxID]) AS [BoxCount],
    SUM(CASE WHEN [b].[Status] = @IN THEN 1 ELSE 0 END)) AS [BoxesIn],
    SUM(CASE WHEN [b].[Status] = @OUT THEN 1 ELSE 0 END) AS [BoxesOut],
    SUM(CASE WHEN [b].[DestructionDate] <= GETDATE() THEN 1 ELSE 0 END) AS [BoxesForDestruction],
FROM [Clients] AS [c] INNER JOIN [Boxes] AS [b]
  ON [c].[ClientID] = [b].[ClientID]
INNER JOIN [Warehouses] AS [w]
  ON [c].WarehouseID = [w].[WarehouseID]
WHERE [c].[ClientID] = @ClientID
GROUP BY
  [c].[ClientID],
  [c].[Name],
  [w].[Name]

计数的输出是正确的。当我将ClientID | ClientName | WarehouseName | BoxCount | BoxesIn | BoxesOut | BoxesForDestruction 1 | ACME Corp. | FooFactory | 22744 | 22699 | 45 | 7888 表添加到Files时,数字会膨胀。这是SQL:

INNER JOIN

这给了我下面的计数输出(我省略了前三列,因为它们不相关):

SELECT
    [c].[ClientID],
    [c].[Name] AS [ClientName],
    [w].[Name] AS [WarehouseName],
    COUNT(DISTINCT [b].[BoxID]) AS [BoxCount],
    COUNT(DISTINCT [f].[FileID]) AS [FileCount], -- *NEW*
    SUM(CASE WHEN [b].[Status] = @IN THEN 1 ELSE 0 END)) AS [BoxesIn],
    SUM(CASE WHEN [b].[Status] = @OUT THEN 1 ELSE 0 END) AS [BoxesOut],
    SUM(CASE WHEN [b].[DestructionDate] <= GETDATE() THEN 1 ELSE 0 END) AS [BoxesForDestruction],
FROM [Clients] AS [c] INNER JOIN [Boxes] AS [b]
  ON [c].[ClientID] = [b].[ClientID]
INNER JOIN [Warehouses] AS [w]
  ON [c].[WarehouseID] = [w].[WarehouseID]
INNER JOIN [Files] AS [f]      -- *NEW*
  ON [b].[BoxID] = [f].[BoxID] -- *NEW*
WHERE [c].[ClientID] = @ClientID
GROUP BY
  [c].[ClientID],
  [c].[Name],
  [w].[Name]

BoxCount | FilesCount | BoxesIn | BoxesOut | BoxesForDestruction 19151 | 411961 | 411381 | 580 | 144615 是正确的,但其他数字已关闭。我知道为什么会这样,但我不知道如何解决它。由于框和文件上的连接返回多行,因此创建了额外的行。执行FilesCount时,额外的行会使计数膨胀。由于仓库只有一行,因此该连接不会影响计数。如何修改我的查询以获取进出仓库的正确数量的文件和框?

1 个答案:

答案 0 :(得分:0)

正如Andomar所提到的,除了Count(*)之外,我还包括了“ as myColumnOne”和“ myColumnTwo”,这是SQL Server 2018所必需的:

 select  *
from    table1 t1
join    (
        select  table1_id
        ,       count(*) as myColumnOne
        from    table2
        group by
                table1_id
        ) t2
on      t2.table1_id = t1.id
join    (
        select  table1_id
        ,       count(*) as myColumnTwo
        from    table3
        group by
                table1_id
        ) t3
on      t3.table1_id = t1.id