聚合后提取特定数据(或所需结果的任何其他解决方案)

Extract Specific Data After a aggregation (Or any other solution for the desired result)

我想 select 2016 年特定 "main_category" 的总计 "sales"

(当年没有销售额的主要类别应显示为零)

我已经成功 select 特定 "main category" 的 "sales" 与所有其他 "main_categories" (没有任何销售) 使用以下查询显示为零:

SELECT 
    mc.name,
    ISNULL(SUM(s.no_of_units * b.unit_price),0) AS tCatSales
FROM Sales s
INNER JOIN Invoice i ON i.invoice_ID = s.invoice_id
INNER JOIN Inventory inv ON inv.inventory_ID = s.inventory_ID
INNER JOIN Batch b ON b.batch_ID = inv.batch_ID
INNER JOIN Products p ON p.product_id = b.product_ID
INNER JOIN Category c ON c.category_ID = p.category_id
RIGHT JOIN Main_Category mc ON mc.cat_id = c.main_category
--WHERE YEAR(i.trans_date) = 2016
GROUP BY mc.name
--HAVING YEAR(i.trans_date)=2016

但是当我尝试通过 WHERE 子句或 HAVING 子句,它将停止显示当年销售额为零的 "main_category" 个名称。

我能想到的一件事是只提供2016年的查询发票 我试图通过做类似的事情来做到这一点,

替换行: INNER JOIN Invoice i ON i.invoice_ID = s.invoice_id

与: INNER JOIN Invoice i ON i.invoice_ID IN (SELECT invoice_id FROM Invoice in2 WHERE Year(in2.trans_date)=2016)

did 显示具有零值但计算的销售额增加的类别(从 2069 到 203151022.75).

我知道这个添加有点不合逻辑并且会破坏整个内部连接,但到目前为止,这些是我能想到或在网络上找到的最接近的东西。

I REPEAT the desired result is: main categories that don't have sales in that year should appear as zero with the year given year/month/date

试试这个:

WHERE ISNULL(YEAR(i.trans_date), 1) = 2016

如果您在外部联接上放置简单的等号条件,它将消除空值,这会给出您想要的零值行。 另请注意,类似:

WHERE YEAR(i.trans_date) = 2016

不可搜索,参见here

正如 Sean 和 Eli 提到的,不推荐使用 RIGHT JOIN,您可以将其更改为 LEFT JOIN,或者使用这样的子查询:

SELECT
    mc.name,
    tCatSales = ISNULL(
      (
        SELECT 
            SUM(s.no_of_units * b.unit_price) AS tCatSales
        FROM Sales s
        INNER JOIN Invoice i ON i.invoice_ID = s.invoice_id
        INNER JOIN Inventory inv ON inv.inventory_ID = s.inventory_ID
        INNER JOIN Batch b ON b.batch_ID = inv.batch_ID
        INNER JOIN Products p ON p.product_id = b.product_ID
        INNER JOIN Category c ON c.category_ID = p.category_id    
        WHERE mc.cat_id = c.main_category  
          AND YEAR(i.trans_date) = 2016
      ) , 0)
FROM Main_Category mc