我有一个查询,我使用SUM来计算帐单明细值。我想创建一个CASE
语句来处理该总和的结果,而不是求和的值。以下是我的查询目前的部分示例。
SELECT
bill.billnumber_id,
billdetail.billclass,
SUM(billdetail.amount) AS Amount
GROUP BY bill.billnumber_id, billdetail.billclass
假设这总计4行billdetail
(2,0,5,3),总和为10.我想根据10个数量做CASE
语句,而不是个人价值观。感谢。
答案 0 :(得分:2)
这是你想要的吗?
SELECT bill.billnumber_id, billdetail.billclass, SUM(billdetail.amount) AS Amount,
(case when SUM(billdetail.amount) > 10 then 'BigOne'
else 'Little'
end)
GROUP BY bill.billnumber_id, billdetail.billclass
答案 1 :(得分:1)
您需要使用子查询:
SELECT CASE WHEN Amount = 0 THEN 'Nothing' ELSE 'somthing' END AmountComment
FROM(
SELECT bill.billnumber_id, billdetail.billclass, SUM(billdetail.amount) AS Amount
GROUP BY bill.billnumber_id, billdetail.billclass
)x
答案 2 :(得分:0)
您可以将其设为子查询:
SELECT billnumber_id, billclass, CASE WHEN Amount = 10 THEN ... ELSE ... END
FROM
(
SELECT bill.billnumber_id, billdetail.billclass, SUM(billdetail.amount) AS Amount
GROUP BY bill.billnumber_id, billdetail.billclass
) A
或者只是重复聚合:
SELECT bill.billnumber_id, billdetail.billclass, SUM(billdetail.amount) AS Amount
, CASE WHEN SUM(billdetail.amount) = 10 THEN ... ELSE ... END
GROUP BY bill.billnumber_id, billdetail.billclass
答案 3 :(得分:0)
SELECT bill.billnumber_id, billdetail.billclass, (Select SUM(billdetail.amount) from billdetail)
AS Amount
from bill inner join billdetail on bill.id = buildetail.kBillId
/* include from join (not added above)*/
GROUP BY bill.billnumber_id, billdetail.billclass
我相信这就是你所追求的......你可能希望在内部选择语句中包含相同的from
结构:
SELECT bill.billnumber_id, billdetail.billclass, (Select SUM(billdetail.amount) from bill inner
join billdetail on bill.id = buildetail.kBillId ) AS Amount
from bill inner join billdetail on bill.id = buildetail.kBillId
/* include from join (not added above)*/
GROUP BY bill.billnumber_id, billdetail.billclass
如果这就是你的意思,请告诉我。