select *
from (select debit
from tblarpayments a
where paymenttype = 6
and credit = 0
and checkid = 522
union
select credit
from tblarpayments b
where paymenttype = 6
and debit = 0
and checkid = 522
union
select debit
from tblarpayments c
where ref# like 'A/R%'
and checkid = 522
union
select credit
from tblarpayments d
where debit = 0
and paymenttype = 2
and checkid = 522
union
select debit
from tblarpayments e
where credit = 0
and ref# not like 'A/R%'
and checkid = 522)
| | DEBIT |
|1| 10.0000 |
|2| 240.0000 |
|3| 250.0000 |
|4| 11540.0000|
我希望它排成一排 喜欢这个
| |DEBIT |CREDIT|DEBIT1 |CREDIT1 |DEBIT2 |
|1|11540.0000| |10.0000|250.0000|240.0000|
损失增值委员会信贷债务 在第二个单元格中,Credit在checkid = 522 debit = 0时没有值coz = 0 paymenttype = 6没有信用值它为null。 全部在一行如何解决?我尝试了很多东西,但我无法理解。
答案 0 :(得分:0)
假设您的每一行返回不超过一行,那么这对您有用:
select t1.debit as LOSS
, t2.credit as GAIN
, t3.debit as COMMISSION
, t4.credit as CREDIT
, t5.debit as DEBIT
from (
select *
from tblarpayments a
where checkid = 522
and paymenttype = 6
and credit = 0
) t1
left outer join (
select *
from tblarpayments a
where checkid = 522
and paymenttype = 6
and debit = 0
) t2 on t1.checkid = t2.checkid
left outer join (
select *
from tblarpayments a
where checkid = 522
and ref# like 'A/R%'
) t3 on t1.checkid = t3.checkid
left outer join (
select *
from tblarpayments a
where checkid = 522
and debit = 0
and paymenttype = 2
) t4 on t1.checkid = t4.checkid
left outer join (
select *
from tblarpayments a
where checkid = 522
and credit = 0
and ref# not like 'A/R%'
) t5 on t1.checkid = t5.checkid
我假设你总是有一个LOSS记录但你可能没有所有记录(你的图像没有显示GAIN的值),我使用了LEFT OUTER JOIN。但是,FULL OUTER JOIN可能更合适:您知道您的数据而我不知道。或者,如果您可以保证每个子查询始终都有记录,那么您应该使用INNER JOIN。
请注意,如果任何子查询确实返回多行,您将获得产品,因此您必须相应地调整过滤器。
编写此查询可能有更多表现方式。但是,如果没有实际的表结构和代表性数据,那么我将编写多少推测性代码是有限制的。
答案 1 :(得分:0)
假设每个条件都有一个匹配行,那么您可以在单个表扫描中执行此操作:
Oracle 11g R2架构设置:
CREATE TABLE tblarpayments ( paymenttype, credit, debit, ref#, checkid ) AS
SELECT 6, 0, 123, NULL, 522 FROM DUAL UNION ALL
SELECT 6, 456, 0, NULL, 522 FROM DUAL UNION ALL
SELECT 6, NULL, 789, 'A/R', 522 FROM DUAL UNION ALL
SELECT 2, 111, 0, NULL, 522 FROM DUAL UNION ALL
SELECT 3, 0, 222, 'X/Y', 522 FROM DUAL;
查询1 :
SELECT MAX( CASE WHEN ( paymenttype, credit ) IN ( ( 6, 0 ) ) THEN debit END ) AS debit,
MAX( CASE WHEN ( paymenttype, debit ) IN ( ( 6, 0 ) ) THEN credit END ) AS credit,
MAX( CASE WHEN ref# LIKE 'A/R%' THEN debit END ) AS debit1,
MAX( CASE WHEN ( paymenttype, debit ) IN ( ( 2, 0 ) ) THEN credit END ) AS credit1,
MAX( CASE WHEN ref# NOT LIKE 'A/R%' AND credit = 0 THEN debit END ) AS debit2
FROM tblarpayments
WHERE ( ( paymenttype, credit ) IN ( ( 6, 0 ) )
OR ( paymenttype, debit ) IN ( ( 6, 0 ), ( 2, 0 ) )
OR ref# LIKE 'A/R%'
OR ( ref# NOT LIKE 'A/R%' AND credit = 0 )
)
AND checkid = 522
<强> Results 强>:
| DEBIT | CREDIT | DEBIT1 | CREDIT1 | DEBIT2 |
|-------|--------|--------|---------|--------|
| 123 | 456 | 789 | 111 | 222 |