我需要合并第1行和第2行。第3和第4行。以下是我已经得到的。 因为货币是NULL所以它没有合并。
下面是我目前的代码。那么如何合并呢?
SELECT
decode(substr(o.tran_no,1,1), 'B', 'BUY', 'S', 'SELL') BS_IND,
COUNT(decode(substr(o.tran_no,1,1), 'B', 'BUY')) BUY,
COUNT(decode(substr(o.tran_no,1,1),'S', 'SELL')) SELL,
DECODE(D.CURRENCY,NULL,'MYR','MYR') CURRENCY3,
DECODE(D.CURRENCY,'MYR',1,NULL,1,0) CUR,
o.client_no,
D.CURRENCY
FROM
bos_m_ledger o, bos_m_para r, bos_m_client c, bos_cltype g, BOS_M_STOCK D
WHERE
r.para_type = 'BRANCH'
AND R.PARA_CODE = O.BRANCH_CODE
and o.client_no = c.client_no
AND O.STOCK_NO = D.STOCK_NO
and g.nbrk_rate = 1
AND CSTAMP_EXPIRY_DATE IS NOT NULL
and c.client_type = g.client_type
and o.tdr_code = c.tdr_code
and o.tran_type = 'CON'
AND C.CLIENT_NO ='3JF0391'
AND C.TDR_CODE >= 'DA1'
AND C.TDR_CODE <= 'ZZZZZZ'
group by
substr(o.tran_no,1,1), o.client_no, o.branch_code, r.descr, c.client_name,
C.TDR_CODE, D.CURRENCY, NVL(D.EXCH_CODE,0)
ORDER BY
O.BRANCH_CODE, C.TDR_CODE, O.CLIENT_NO
答案 0 :(得分:1)
使用聚合:
SELECT (CASE WHEN o.tran_no LIKE 'B%' THEN 'BUY'
WHEN o.tran_no LIKE 'S%' THEN 'SELL'
END) as BS_IND,
SUM(CASE WHEN o.tran_no LIKE 'B%' THEN 1
ELSE 0
END) as Buy,
SUM(CASE WHEN o.tran_no LIKE 'S%' THEN 1
ELSE 0
END) as sell,
COALESCE(D.CURRENCY, 'MYR') as CURRENCY3,
(CASE WHEN(D.CURRENCY = 'MYR' OR D.CURRENCY IS NULL THEN 1 ELSE 0 END) as Cur)
o.client_no, D.CURRENCY
FROM bos_m_ledger o JOIN
bos_m_para r
ON R.PARA_CODE = O.BRANCH_CODE JOIN
bos_m_client c
ON o.client_no = c.client_no AND o.tdr_code = c.tdr_code JOIN
bos_cltype g
ON c.client_type = g.client_type
BOS_M_STOCK D
ON O.STOCK_NO =D.STOCK_NO
WHERE r.para_type='BRANCH' AND
g.nbrk_rate = 1 AND
CSTAMP_EXPIRY_DATE IS NOT NULL AND
o.tran_type = 'CON' AND
C.CLIENT_NO='3JF0391' AND
C.TDR_CODE >='DA1' AND
C.TDR_CODE <='ZZZZZZ'
group by (CASE WHEN o.tran_no LIKE 'B%' THEN 'BUY'
WHEN o.tran_no LIKE 'S%' THEN 'SELL'
END),
o.client_no
ORDER BY O.CLIENT_NO;
一路走来,加入现代世界:
JOIN
语法一直是SQL语言的一部分。使用它。decode()
是特定于Oracle的。学习条件表达式的正确SQL。答案 1 :(得分:0)
你可以在你的sql
的顶部使用它 with tab as
(select 'buy' bs_i, 10 buy, 0 sell, 'myr' cur, 1 cur1, '3jfo391' client, 'myr' currency
union all
select 'buy' bs_i, 11 buy, 0 sell, 'myr' cur, 1 cur1, '3jfo391' client, null currency
union all
select 'sell' bs_i, 0 buy, 11 sell, 'myr' cur, 1 cur1, '3jfo391' client, 'myr' currency
union all
select 'sell' bs_i, 0 buy, 10 sell, 'myr' cur, 1 cur1, '3jfo391' client, null currency
)
select bs_i, sum(buy), sum(sell), max(cur), max(cur1), max(client), max(currency)
from tab
group by bs_i;
O / P:
bs_i sum sum max max max max
buy 21 0 myr 1 3jfo391 myr
sell 0 21 myr 1 3jfo391 myr