我对这个很难过。我为emplid获得了两列sql结果,但不知道如何将它们组合成1.任何人都知道如何?我正在使用oracle。这是sql:
SELECT ee.emplid, mem.emplid
FROM ps_employees ee, ps_vc_plan_mem mem
WHERE ee.empl_status IN ('A', 'L')
AND ee.emplid NOT IN (SELECT vc.emplid
FROM ps_vc_plan_mem vc
WHERE vc.vc_plan_id in ('PNC-RS','PNC-SO','PNC-ESPP'))
AND ee.emplid IN
(SELECT srv.emplid
FROM ps_Z_ADD_EMP_SRVDT srv
WHERE srv.emplid = ee.emplid
AND srv.z_serv_dt_type = 'ESP'
AND service_dt <= (SELECT asofdate FROM psasofdate))
OR mem.vc_plan_id in ('PNC-RS','PNC-SO','PNC-ESPP')
答案 0 :(得分:1)
在这种情况下,您需要一个UNION
,它是一个与另一个结果集(第二列)连接的结果集(第一列)。它看起来像这样:
SELECT ee.emplid
FROM ps_employees ee, ps_vc_plan_mem mem
WHERE ee.empl_status IN ('A', 'L')
AND ee.emplid NOT IN (SELECT vc.emplid
FROM ps_vc_plan_mem vc
WHERE vc.vc_plan_id in ('PNC-RS','PNC-SO','PNC-ESPP'))
AND ee.emplid IN
(SELECT srv.emplid
FROM ps_Z_ADD_EMP_SRVDT srv
WHERE srv.emplid = ee.emplid
AND srv.z_serv_dt_type = 'ESP'
AND service_dt <= (SELECT asofdate FROM psasofdate))
OR mem.vc_plan_id in ('PNC-RS','PNC-SO','PNC-ESPP')
--Here's the use of UNION
UNION ALL
--Seond query is the same, just returning the "other" column
SELECT mem.emplid
FROM ps_employees ee, ps_vc_plan_mem mem
WHERE ee.empl_status IN ('A', 'L')
AND ee.emplid NOT IN (SELECT vc.emplid
FROM ps_vc_plan_mem vc
WHERE vc.vc_plan_id in ('PNC-RS','PNC-SO','PNC-ESPP'))
AND ee.emplid IN
(SELECT srv.emplid
FROM ps_Z_ADD_EMP_SRVDT srv
WHERE srv.emplid = ee.emplid
AND srv.z_serv_dt_type = 'ESP'
AND service_dt <= (SELECT asofdate FROM psasofdate))
OR mem.vc_plan_id in ('PNC-RS','PNC-SO','PNC-ESPP')
如果您希望结果具有不同的值,请使用UNION
代替UNION ALL
,但除此之外,您已完全设定。
答案 1 :(得分:1)
如果我遵循逻辑,您只想将当前的交叉连接拆分为单独的查询并将结果合并在一起;并且你可能会丢失其中一个过滤器,因为它是多余的:
SELECT ee.emplid,
FROM ps_employees ee
WHERE ee.empl_status IN ('A', 'L')
AND ee.emplid IN
(SELECT srv.emplid
FROM ps_Z_ADD_EMP_SRVDT srv
WHERE srv.emplid = ee.emplid
AND srv.z_serv_dt_type = 'ESP'
AND service_dt <= (SELECT asofdate FROM psasofdate))
UNION ALL
SELECT mem.emplid
FROM ps_vc_plan_mem mem
WHERE mem.vc_plan_id in ('PNC-RS','PNC-SO','PNC-ESPP')
union
消除了重复项,因此您无需明确排除下半部分出现的前半部分的值。
如果查询的任何一部分可以自己生成重复项 - 相同的ee.emplid
可以出现两次,比如说 - 那么这也会抑制那些重复项。如果它们可以存在并且您想要显示它们,那么您需要使用union all
代替,并且在这种情况下您可能希望恢复not exists
子句。
Read more about the union
operator
如果您想要一个整体计数,那么您可以将其包装为内联视图:
SELECT COUNT(*)
FROM (
SELECT ee.emplid,
FROM ps_employees ee
WHERE ee.empl_status IN ('A', 'L')
AND ee.emplid IN
(SELECT srv.emplid
FROM ps_Z_ADD_EMP_SRVDT srv
WHERE srv.emplid = ee.emplid
AND srv.z_serv_dt_type = 'ESP'
AND service_dt <= (SELECT asofdate FROM psasofdate))
UNION ALL
SELECT mem.emplid
FROM ps_vc_plan_mem mem
WHERE mem.vc_plan_id in ('PNC-RS','PNC-SO','PNC-ESPP')
)