我在数据库中有4个表。仓库包含客户拥有的箱子,箱子中有文件。有Client
表,Warehouse
表,Boxes
表和Files
表。
因此Client
表有WarehouseID
作为外键,Boxes
表有ClientID
作为外键,Files
表有{ {1}}作为外键。我想计算每个客户在查询中包含的方框和文件的数量,以及进出仓库的方框数。 BoxID
和Status
表上的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
时,额外的行会使计数膨胀。由于仓库只有一行,因此该连接不会影响计数。如何修改我的查询以获取进出仓库的正确数量的文件和框?
答案 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