我想在CASE语句中应用计算,但结果不是我预期的,我不知道如何应用查询来过滤日期(取决于月份)。我的查询有什么问题?请帮忙......谢谢
这是我的查询
SELECT DISTINCT a.SERVICE_CODE,
CASE WHEN
b.SERVICE_CODE IS NULL THEN a.AMT ELSE SUM (a.AMT) - SUM(b.AMT) END AS TOTAL_AMT
FROM Table a
LEFT OUTER JOIN Table b ON (a.SERVICE_CODE = b.SERVICE_CODE)
WHERE b.SERVICE_CODE >='3000' AND c.SERVICE_CODE >='3000'
表a
Invoice_No date Service_code Amt
001 1/7/2014 6000 300
002 1/8/2014 6003 700
003 5/8/2014 6003 100
004 10/8/2014 6005 1000
表b
Credit_No date Service_code Amt
c100 1/7/2014 6000 300
c200 13/8/2014 6003 700
期望的输出
Service_code Total_Amt
6003 100
6005 1000
谢谢
答案 0 :(得分:0)
试试这个
在MYSQL
select t1.SERVICE_CODE,(t1.amt- case when c.amt is null then 0 else c.amt end)
as AMT from t1 c right outer join (select t.Invoice_No,SERVICE_CODE,
sum(amt) as amt from t group by SERVICE_CODE) as t1
on c.SERVICE_CODE=t1.SERVICE_CODE
inner join tablea a on a.invoice_no=t1.Invoice_No
答案 1 :(得分:0)
试试这个:
select
bcode,
case
when ccode is null then bamt
else bamt - camt
end as amt
from
(select service_code bcode, sum(amt) bamt
from b
where service_code >= 3000
group by service_code) b
left join
(select service_code ccode, sum(amt) camt
from c
where service_code >= 3000
group by service_code) c on b.bcode = c.ccode
order by bcode
根据示例数据,表b
可能包含表service_code
可能不会c
的值。因此,请使用左外部联接来链接b
和c
。此外,由于invoice_no
不需要显示在输出中,因此您根本不需要加入a
。