我的数据如下所示(通常超过2条记录)
OBLIGOR OBN_NUM XPTYPE NET_UNUSED BANK_ASSET
-------------------------------------------------
1 000100000 0101 100 0
1 000100001 5151 100 0
1 000100002 5151 50 0
当我使用以下SQL时,我只能求和为100。但我想得到250。
SELECT
SUM(NET_UNUSED) + SUM(BANK_ASSET) AS BANK_ASSET,
OBLIGOR AS OBLIGOR,
SUBSTRING (OBN_NUM,1,4) AS OBN_NUM
FROM
RB_CRM_DEV.[IN].STG_SF_I_DC
WHERE
SUBSTRING (OBN_NUM,1,4) = SUBSTRING (OBN_NUM,1,4)
AND SUBSTRING( XPTYPE,1,1) IN (0,1)
GROUP BY
OBLIGOR, SUBSTRING (OBN_NUM, 1, 4)
ORDER BY
OBLIGOR, SUBSTRING(OBN_NUM, 1, 4)
如何确保我的记录集至少应包含xptype as 0,1
条记录才能在此查询中检查(因为SUBSTRING(XPTYPE,1,1) IN (0,1)
条件会删除其他两条记录)。
答案 0 :(得分:0)
好吧,如果我正确理解了您的要求,那么您所追求的就是xptype以0或1开头的Obligor的任何记录的存在,例如,您可以使用EXISTS
检查一下:
SELECT SUM(NET_UNUSED)+SUM(BANK_ASSET) AS BANK_ASSET, OBLIGOR AS OBLIGOR,
SUBSTRING (OBN_NUM,1,4) AS OBN_NUM
FROM RB_CRM_DEV.[IN].STG_SF_I_DC A
WHERE EXISTS (
SELECT 1 FROM RB_CRM_DEV.[IN].STG_SF_I_DC B
WHERE SUBSTRING (A.OBN_NUM,1,4) = SUBSTRING (B.OBN_NUM,1,4)
AND A.OBLIGOR = B.OBLIGOR
AND SUBSTRING( B.XPTYPE,1,1) IN (0,1)
)
GROUP BY OBLIGOR, SUBSTRING (OBN_NUM,1,4)
ORDER by OBLIGOR,SUBSTRING(OBN_NUM,1,4)
应该工作。如果这不是您想要的,请用更多示例数据编辑您的问题,以准确显示您想要的内容。
答案 1 :(得分:0)
使用连接的另一种方法-
SELECT Sum(t1.net_unused) + Sum(t1.bank_asset) AS BANK_ASSET,
t1.obligor AS OBLIGOR,
Substring (t1.obn_num, 1, 4) AS OBN_NUM
FROM rb_crm_dev.[IN].stg_sf_i_dc t1
INNER JOIN (SELECT obligor,
obn_num
FROM rb_crm_dev.[IN].stg_sf_i_dc
WHERE Substring(xptype, 1, 1) IN ( 0, 1 )) t2
ON t1.obligor = t2.obligor
AND Substring (t1.obn_num, 1, 4) =
Substring (t2.obn_num, 1, 4)
GROUP BY t1.obligor,
t1.Substring (obn_num, 1, 4)
ORDER BY t1.obligor,
t1.Substring(obn_num, 1, 4)