我有一个查询,用于计算特定客户端的前缀数量(QTY)的总和/数量。已使用前缀代替产品来减少版本/命名变体。
此查询在两个由外键链接的单独表上运行,其中client_ID是第三个表中的共享属性和主键。一个表称为已购买,另一个表称为已安装。
我正在尝试计算安装数量和购买数量之间的差异以及每个表格中的一些其他字段。这个概念类似于股票支票(Amountinstock - AmountSold)。
我遇到的问题是这会在结果上创建交叉连接。避免交叉连接的方法是什么?外部,右侧或左侧连接是解决此问题还是我需要使用union语句。
表格如下:
Client ( Client_ID*, Client)
Purchased (Client_ID, Product, Prefix, License Status, Amount, Deployed at, Start_date, End_date)
Installed (Client_ID, Product, Prefix, Publisher, Version, Domain, Server, Amount)
*Primary Key
前缀&的数量。客户端查询代码是:
SELECT
Installed.Client_ID,
Client.Client,
Installed.Prefix,
SUM(Installed.Amount) AS QuantityofLicensesInstalled
FROM Installed
INNER JOIN Client
ON Installed.Client_ID=Client.Client_ID
GROUP BY Installed.Client_ID, Installed.Prefix, Client.Client;
尝试加入结果的代码是:
SELECT
Installed.Prefix,
QuantityofLicensesInstalled,
Purchased.Prefix,
QuantityofLicensesPurchased,
(QuantityofLicensesInstalled-QuantityofLicensesPurchased) AS Differencebetweenvalues
FROM ClientIDPrefixSumInstalled, ClientIDPrefixSumPurchased;
目前正在生成交叉连接结果。
答案 0 :(得分:2)
首先:从selectID子句和group by中删除ClientIDPrefixSumPurchased和ClientIDPrefixSumInstalled的客户端列。
然后这可能会产生你需要的东西。
SELECT
Installed.Prefix,
QuantityofLicensesInstalled,
Purchased.Prefix,
QuantityofLicensesPurchased,
(QuantityofLicensesInstalled-QuantityofLicensesPurchased) AS Differencebetweenvalues
FROM ClientIDPrefixSumInstalled
full outer join ClientIDPrefixSumPurchased on installed.prefix = purchased.prefix;
答案 1 :(得分:0)
获取两个表中存在的所有前缀的单个列表,获取每个表中每个前缀的总量,然后将总计加入前缀列表以计算差异。
SELECT
c.Client,
a.Prefix,
IFNULL(i.SumAmount, 0) - IFNULL(p.SumAmount, 0) AS AmountDiff
FROM (
SELECT Client_ID, Prefix
FROM Installed
UNION
SELECT Client_ID, Prefix
FROM Purchased
) a
INNER JOIN Client c ON a.Client_ID = c.Client_ID
LEFT JOIN (
SELECT Client, Prefix, SUM(Amount) AS SumAmount
FROM Installed
GROUP BY Client, Prefix
) i
ON a.Client_ID = i.Client_ID AND a.Prefix = i.Prefix
LEFT JOIN (
SELECT Client, Prefix, SUM(Amount) AS SumAmount
FROM Purchased
GROUP BY Client, Prefix
) p ON a.Client_ID = p.Client_ID AND a.Prefix = p.Prefix