我正在运行一个查询,该查询按某个日期范围内的类别或子类别汇总销售信息。我被要求为其添加预算信息,以显示此查询提取的信息的报告。
SELECT
DATE_FORMAT(B.TxnDate, "%Y-%m") AS FormattedTxnDate,
SUM(B.Quantity) AS QuantitySum,
SUM(B.Quantity * B.Amount) AS Revenue,
SUM(CASE WHEN B.AverageCost = 0 THEN (B.Quantity * C.PurchaseCost) ELSE (B.Quantity *
B.AverageCost) END) AS COGS,
A.CustomerRefFullName,
SUM(D.Budget_2018) AS Budget,
D.Brand, D.Category, D.Subcategory, D.ProductManager, C.VendorRefFullName
FROM
qb_invoice_info A, qb_invoice_line_info B, qb_item_info C, qb_item_group D
WHERE
A.TxnID = B.TxnID
AND
B.Item_ListID = C.ListID
AND
C.Parent_ListID = D.ListID
AND
(C.Type = "Inventory" OR C.Type = "InventoryAssembly")
AND
B.TxnDate BETWEEN ? AND ?
GROUP
BY D.Category, YEAR(B.TxnDate), QUARTER(B.TxnDate)
ORDER
BY D.Category ASC, YEAR(B.TxnDate) ASC, QUARTER(B.TxnDate) ASC
每个子类别都有自己的预算金额。问题是某些子类别共享所有相同的信息,除了它们的唯一ID。在qb_item_group表中,一些记录可能如下所示。
qb_item_group
id | Category | Subcategory | Budget
------------------------------------
1A | Lights | DMX | 4000
1B | Lights | DMX | 4000
1C | Lights | DMX | 4000
2A | Lights | Flash | 5000
3A | Lights | Bulbs | 1000
在这种情况下,灯光的总预算将为10,000,因为我们忽略了两个DMX预算。我今天早些时候尝试SUM(DISTINCT D.Budget_2018 AS Budget
,但它失败了,因为它只是添加了唯一的预算值。我如何调整上面的查询,以便我可以按类别或子类别检索所有销售记录,但仍然得到总预算,即父类别下所有唯一子类别的总和?
答案 0 :(得分:2)
SELECT
DATE_FORMAT(B.TxnDate, "%Y-%m") AS FormattedTxnDate,
SUM(B.Quantity) AS QuantitySum,
SUM(B.Quantity * B.Amount) AS Revenue,
SUM(
CASE
WHEN B.AverageCost = 0 THEN (B.Quantity * C.PurchaseCost)
ELSE (B.Quantity * B.AverageCost)
END
) AS COGS,
A.CustomerRefFullName,
COALESCE(category_budgets.budget, 0) AS budget,
D.Brand,
D.Category,
D.Subcategory,
D.ProductManager,
C.VendorRefFullName
FROM
qb_invoice_info A,
qb_invoice_line_info B,
qb_item_info C,
qb_item_group D
LEFT JOIN
(
SELECT
a.category,
SUM(a.budget) as budget
FROM
(
SELECT DISTINCT
category
budget
FROM
budgets
) a
) category_budgets
ON
category_budgets.category = D.category
WHERE
A.TxnID = B.TxnID
AND
B.Item_ListID = C.ListID
AND
C.Parent_ListID = D.ListID
AND
(C.Type = "Inventory" OR C.Type = "InventoryAssembly")
AND
B.TxnDate BETWEEN ? AND ?
GROUP BY
D.Category, YEAR(B.TxnDate), QUARTER(B.TxnDate)
ORDER BY
D.Category ASC, YEAR(B.TxnDate) ASC, QUARTER(B.TxnDate) ASC
;
您可以使用不同类别和预算的总和来保持联接。这将为您提供所需的所有输出行,但也会为预算表中没有条目的类别提供$ 0预算。祝你好运!