我有一个名为 PM_BATCH_ST 的表,如下所示:
BATCH_ID | 结果 |
---|---|
1000564932 | 国际学习中心 |
1000564932 | 有限责任公司 |
1000585739 | 国际学习中心 |
1000585739 | 有限责任公司 |
1000384769 | 国际学习中心 |
1000384769 | 有限责任公司 |
1000384757 | 有限责任公司 |
1000888940 | 国际学习中心 |
我可以过滤表以获得同时具有 ISC 条目和 LLC 条目的 BATCH_ID 吗? 所以我想要的答案是:
1000564932
1000585739
1000384769
SELECT BATCH_ID
FROM PM_BATCH_ST
WHERE RESULT IN ('ISC', 'LLC')
GROUP BY BATCH_ID
HAVING COUNT(DISTINCT RESULT) = 2;
我认为以下方法可以做到:
select distinct batch_id
from PM_BATCH_ST a
where a.result = 'ISC' and
exists (
select 1
from PM_BATCH_ST b
where a.batch_id=b.batch_id
and b.result='LLC'
)
这可以使用
INTERSECT
来完成
SELECT BATCH_ID
FROM PM_BATCH_ST
WHERE RESULT = 'ISC'
INTERSECT
SELECT BATCH_ID
FROM PM_BATCH_ST
WHERE RESULT = 'LLC'
结果:
BATCH_ID
1000384769
1000564932
1000585739
对于 2 个值,我只需 self-
JOIN
并使用像这样的 WHERE
子句:
SELECT st1.BATCH_ID
FROM PM_BATCH_ST st1
JOIN PM_BATCH_ST st2 ON st1.BATCH_ID = st2.BATCH_ID
WHERE st1.RESULT = 'ISC' AND st2.RESULT = 'LLC'
这应该给你所有
BATCH_ID
同时拥有ISC
和LLC
作为RESULT
SQL Fiddle 结果:
BATCH_ID |
---|
1000564932 |
1000585739 |
1000384769 |
CREATE TABLE PM_BATCH_ST (
BATCH_ID INT,
RESULT TEXT
);
INSERT INTO PM_BATCH_ST (BATCH_ID, RESULT)
VALUES
(1000564932, 'ISC'),
(1000564932, 'LLC'),
(1000585739, 'ISC'),
(1000585739, 'LLC'),
(1000384769, 'ISC'),
(1000384769, 'LLC'),
(1000384757, 'LLC'),
(1000888940, 'ISC');
/* @Qubicon has the most tighten-up answer. Below is another way of doing it*/
WITH ISC_table AS (
SELECT *
FROM PM_BATCH_ST
WHERE CONVERT(VARCHAR, RESULT) IN ('ISC')
),
LLC_table AS (
SELECT *
FROM PM_BATCH_ST
WHERE CONVERT(VARCHAR, RESULT) IN ('LLC')
)
SELECT
t1.BATCH_ID AS BATCH_ID
FROM ISC_table AS t1
INNER JOIN LLC_table AS t2
ON t1.BATCH_ID = t2.BATCH_ID;
BATCH_ID |
---|
1000564932 |
1000585739 |
1000384769 |