我要加入以下表格和列:
1. CUSTOMERS: customer_id,source_system
2. ALERT_CASE_HEADER: customer_id,data_source_id
3. DATA_SOURCE:id,name
查询是检索CUSTOMERS.source_system,表CUSTOMERS和ALERT_CASE_HEADER中的customer_id都是链接的。
但是,如果DATA_SOURCE.name='Interactive'
,源系统默认为“NIL
”,则会将data_source_id and id
列链接起来。
我正在考虑加入他们,但是CUSTOMERS和DATA_SOURCE之间似乎没有关系来确定它是否是“互动”
SELECT SOURCE_SYSTEM FROM CUSTOMERS CUS INNER JOIN
ALERT_CASE_HEADER ACH ON ACH.CUSTOMER_ID = CUS.CUSTOMER_ID INNER JOIN
ALERT_CASE_HEADER ACH ON ACH.CUSTOMER_ID = CUS.CUSTOMER_ID WHERE
ACH.DATASOURCE_ID=(SELECT DS.ID FROM DATA_SOURCE DS WHERE
DS.NAME='Interactive');
上面的查询已经修复,所以我把它作为子查询之一,如下所示。该查询返回CUSTOMERS.Source_System和ORGANIZATION_UNITS.ORGUNIT_CODE的每个STATUSES.Name和group的计数。预期的结果是显示所有计数,包括DATA_SOURCE.Name ='NA'。由于子查询返回多行,查询不符合目的。
SELECT
(SELECT CASE WHEN DS.NAME = 'Interactive' THEN 'NA' ELSE CUS.SOURCE_SYSTEM END AS SOURCE_SYSTEM
FROM CUSTOMERS CUS
INNER JOIN ALERT_CASE_HEADER ACH ON ACH.CUSTOMER_ID = CUS.CUSTOMER_ID
INNER JOIN DATA_SOURCE DS ON ACH.DATASOURCE_ID = DS.ID),
ORG.ORGUNIT_CODE AS ORGANIZATION_UNITS,
SUM(
CASE
WHEN S.NAME = 'Pending' THEN 1 ELSE 0
END
) AS PENDING,
SUM(
CASE
WHEN S.NAME = 'New' THEN 1 ELSE 0
END
) AS NEW,
SUM(
CASE
WHEN S.NAME = 'Investigation' THEN 1 ELSE 0
END
) AS INVESTIGATION,
SUM(
CASE
WHEN S.NAME = 'Escalated' THEN 1 ELSE 0
END
) AS ESCALATED,
SUM(
CASE
WHEN S.NAME = 'Recommend' THEN 1 ELSE 0
END
) AS RECOMMEND,
SUM(
CASE
WHEN S.NAME = 'Reopen' THEN 1 ELSE 0
END
) AS REOPEN
FROM
STATUSES S
JOIN ALERT_ITEM AI ON S.ID = AI.STATUS_ID
JOIN ALERT_CASE_HEADER ACH ON AI.ENTITY_KEY = ACH.ALERT_KEY
INNER JOIN ORGANIZATION_UNITS ORG ON ORG.ID = ACH.CUSTOMER_ORGUNIT_ID
INNER JOIN CUSTOMERS CUS ON CUS.CUSTOMER_ID = ACH.CUSTOMER_ID
WHERE AI.ENTITY_NAME = 'Active Alert'
GROUP BY ORG.ORGUNIT_CODE,CUS.SOURCE_SYSTEM;
答案 0 :(得分:1)
我认为您可以直接进行一系列连接,然后使用CASE
表达式来呈现源系统的最终值:
SELECT
CASE WHEN ds.NAME = 'Interactive' THEN 'NIL' ELSE c.SOURCE_SYSTEM END AS SOURCE_SYSTEM
FROM CUSTOMERS c
INNER JOIN ALERT_CASE_HEADER ach
ON ach.CUSTOMER_ID = c.CUSTOMER_ID
INNER JOIN DATA_SOURCE ds
ON ach.DATASOURCE_ID = ds.ID
作为注释,如果您怀疑由于与其他表不匹配而可能过滤掉记录,您可能希望进行上述一个或两个联接LEFT JOIN
。此外,在您的原始查询中,您加入了ALERT_CASE_HEADER
两次,这是不必要的。