我有一段非常困难的时间试图让我的结果显示他们需要他们显示...这里和我的查询的样子和下面的例子将是我需要的结果...
iv在这方面已经有很长一段时间尝试案例陈述和加入,但没有运气,如果有人可以帮助我会非常感激。
table name dbo.DTLPAYMENTS
columns
PTNO
CD
AMT
DESCRIPTION
我的查询将结果显示给我,就像这样...也没有相同数额的信用额度和借方。所以一个人可以获得更多借记(> 0)而不是贷记(< 0),反之亦然....
PTNO / CD / AMT / DESCRIPTION
10007558931 30073 688.82 PAYMENT-ME
10007558931 30073 -704.44 PAYMENT-ME
10007558931 30073 704.44 PAYMENT-ME
10007558931 30073 -688.82 PAYMENT-ME
10007558931 30073 -698.82 PAYMENT-ME
我需要在单独的列中借记和贷记 如果有任何可能的方法,我可以将结果发回给我......
PTNO / CD / AMT / DESCRIPTION / CD / AMT / DESCRIPTION
10007558931 30073 688.82 PAYMENT-ME 30073 -688.82 PAYMENT-ME
10007558931 30073 704.44 PAYMENT-ME 30073 -698.82 PAYMENT-ME
10007558931 30073 -704.44 PAYMENT-ME
感谢你,如果有人可以帮助我
答案 0 :(得分:0)
首先,使用CTE将Credits和Debits分成单独的数据集,然后根据AMT的PTNO,CD和反向值(* -1)完全加入它们。
编辑:由于基于AMT的加入不是目标,我使用BatchSeqID作为按时间顺序对数据进行排序的方法。使用ROW_NUMBER()对两个数据集进行排序,然后我加入了这个值。
;WITH
Credit AS
( SELECT PTNO,CD,AMT,DESCRIPTION,
ROW_NUMBER()OVER(PARTITION BY PTNO,CD ORDER BY BatchSeqID) AS Sort
FROM dbo.DTLPAYMENTS
WHERE AMT < 0 ),
Debit AS
( SELECT PTNO,CD,AMT,DESCRIPTION,
ROW_NUMBER()OVER(PARTITION BY PTNO,CD ORDER BY BatchSeqID) AS Sort
FROM dbo.DTLPAYMENTS
WHERE AMT > 0 )
SELECT ISNULL(c.PTNO,d.PTNO) AS PTNO,
ISNULL(c.CD,d.CD) AS CD,
--Credit data
c.AMT AS CRAMT,
c.DESCRIPTION AS CRDESCRIPTION,
--Debit data
d.AMT AS DBTAMT,
d.DESCRIPTION AS DBTDESCRIPTION
FROM Credit c
FULL JOIN Debit d
ON d.PTNO = c.PTNO
AND d.CD = c.CD
AND d.Sort= c.Sort
答案 1 :(得分:0)
如果您不喜欢Matt的解决方案以及重复行的风险,您可以将每笔交易放在不同的行上:
SELECT PTNO,
CASE WHEN AMT < 0 THEN cd ELSE null END DBTCD,
CASE WHEN AMT < 0 THEN amt ELSE null END AMTCD,
CASE WHEN AMT < 0 THEN DESCRIPTION ELSE null END DBTDESCRIPTION,
CASE WHEN AMT > 0 THEN cd ELSE null END CRCD,
CASE WHEN AMT > 0 THEN amt ELSE null END CRAMT,
CASE WHEN AMT > 0 THEN DESCRIPTION ELSE null END CRDESCRIPTION
FROM TABLE1
order by PTNO, AMT
Here你可以看到并发挥结果。
PTNO DBTCD AMTCD DBTDESCRIPTION CRCD CRAMT CRDESCRIPTION
10007558931 30073 -704 PAYMENT-ME (null) (null) (null)
10007558931 30073 -699 PAYMENT-ME (null) (null) (null)
10007558931 30073 -689 PAYMENT-ME (null) (null) (null)
10007558931 (null) (null) (null) 30073 689 PAYMENT-ME
10007558931 (null) (null) (null) 30073 704 PAYMENT-ME
答案 2 :(得分:0)
假设您要根据amt
列的大小对输出进行排序,请尝试:
select ptno,
max(case sign(amt) when 1 then cd end) dr_cd,
max(case sign(amt) when 1 then amt end) dr_amt,
max(case sign(amt) when 1 then description end) dr_desc,
max(case sign(amt) when -1 then cd end) cr_cd,
max(case sign(amt) when -1 then amt end) cr_amt,
max(case sign(amt) when -1 then description end) cr_desc
from (select d.*,
row_number() over (partition by ptno, cd, sign(amt)
order by abs(amt)) rn
from DTLPAYMENTS d) sq
group by ptno, cd, rn
order by ptno, cd, rn
SQLFiddle here。