提问人:Dusty 提问时间:8/26/2023 最后编辑:Dusty 更新时间:8/26/2023 访问量:47
按结果分组中需要零值的类别
Category with zero value required in group by result
问:
我正在使用具有只读权限的 SQL SS。我使用的数据有 3 种产品类型,但我需要一个结果,显示 6 种产品类型的交易总和,其中 3 种不可用的值为零:
示例结果:
产品类型 | 交易总数 |
---|---|
产品类型 1 | £500,000 |
产品类型 2 | £1,000,000 |
产品类型 3 | £0.00 |
产品类型 4 | £750,000 |
产品类型 5 | £0.00 |
产品类型 6 | £0.00 |
产品类型 3、5 和 6 在表中不存在,因此将始终为零,但需要在结果中。所有产品类型也需要根据条件重命名。
我尝试了一个按产品类型分组的 Case 表达式,该表达式适用于 3 种可用的产品类型,这就是我所拥有的:
SELECT
CASE
WHEN Product Type = 'XYZ' AND Criteria1 = 'Y' THEN 'Product Type 1'
WHEN Product Type = 'ABC' AND Criteria1 = 'Y' THEN 'Product Type 2'
WHEN Product Type = 'DEF' AND Criteria1 = 'N' THEN 'Product Type 4'
END as "Product Type",
sum(Transactions) as "Total Transactions"
from ProductTable inner join TransactionTable on ProductCode = TransactionProductCode
where TransactionDate BETWEEN 'Date1' and 'Date2'
GROUP BY
CASE
WHEN Product Type = 'XYZ' AND Criteria1 = 'Y' THEN 'Product Type 1'
WHEN Product Type = 'ABC' AND Criteria1 = 'Y' THEN 'Product Type 2'
WHEN Product Type = 'DEF' AND Criteria1 = 'N' THEN 'Product Type 4'
END
任何实现示例结果的建议将不胜感激,谢谢!
答:
0赞
Isolated
8/26/2023
#1
您应该使用 并将日期条件移动到 join 子句。您还可以在求和时返回 0 而不是 null。left join
coalesce
所以它是这样的:
select
--case expression here,
sum(coalesce(t.amount, 0)) as total_transactions
from products p
left join transactions t
on p.productId = t.productId
and t.some_date between date1 and date2
group by --case expression
评论
0赞
Dusty
9/7/2023
您好,感谢您的回答!不幸的是,它仍然不起作用,您建议我使用什么(我在案例表达式中假设)在结果中获取产品类型 3、5 和 6?非常感谢!
上一个:SQL 额外的空行
评论