我有两张桌子A和B.
两个表都有一列Prod_id,即两个表都可以在这个列上连接,如
A.Prod_id = B.Prod_id
Prod_Id不是这两个表中任何一个的主键。两个表有不同的主键列。
Prod_id列具有以下值:
prod_id -------------- 111 222 111 333 222
B Prod_id列具有以下值:
prod_id -------------- 111 222 111 111 333 222 333
与A表中相同Prod_id的行数相比,任何Prod_Id的B表总是有更多(111,333)或相同(222)行数。
我必须编写一个查询来找出那些B表比A表有更多行数的Prod_id。
我还有其他条件,我必须在where子句中使用其他列。但这些与此无关。
你能帮帮我吗?我是SQL的新手。答案 0 :(得分:1)
试试这个:
SELECT b.prod_id
FROM (
SELECT prod_id, COUNT(*) AS prodCount
FROM tableA
GROUP BY prod_id
) a
INNER JOIN (
SELECT prod_id, COUNT(*) AS prodCount
FROM tableB
GROUP BY prod_id
) b ON a.prod_id = b.prod_id
WHERE b.prodCount > a.prodCount
这得到tableA中每个prod_id的计数,并且在tableB中,通过prod_id加入它们并验证B中出现的次数多于A中的次数。
正如Gordon所建议的,这里有一个版本,考虑到tat tableA没有prod_id记录的可能性:
SELECT b.prod_id
FROM (
SELECT prod_id, COUNT(*) AS prodCount
FROM tableA
GROUP BY prod_id
) a
RIGHT JOIN (
SELECT prod_id, COUNT(*) AS prodCount
FROM tableB
GROUP BY prod_id
) b ON a.prod_id = b.prod_id
WHERE b.prodCount > a.prodCount
OR a.prod_id IS NULL
对于这些记录,a.prod_is将为NULL,因为我们正在进行正确的连接。
答案 1 :(得分:0)
假设您的主键名为pk
,这将产生您想要的结果:
select
b.prod_id,
count(distinct a.pk),
count(distinct b.pk)
from
b left join a on a.prod_id = b.prod_id
group by
b.prod_id
having
count(distinct b.pk) > count(distinct a.pk)
答案 2 :(得分:0)
Oracle 11g R2架构设置:
CREATE TABLE a ( prod_id ) AS
SELECT 111 FROM DUAL
UNION ALL SELECT 222 FROM DUAL
UNION ALL SELECT 111 FROM DUAL
UNION ALL SELECT 333 FROM DUAL
UNION ALL SELECT 222 FROM DUAL;
CREATE TABLE b ( prod_id ) AS
SELECT 111 FROM DUAL
UNION ALL SELECT 222 FROM DUAL
UNION ALL SELECT 111 FROM DUAL
UNION ALL SELECT 111 FROM DUAL
UNION ALL SELECT 333 FROM DUAL
UNION ALL SELECT 222 FROM DUAL
UNION ALL SELECT 333 FROM DUAL;
查询1 :
SELECT prod_id
FROM a
GROUP BY prod_id
HAVING COUNT(1) < (SELECT COUNT(1) FROM b WHERE a.prod_id = b.prod_id )
<强> Results 强>:
| PROD_ID |
|---------|
| 333 |
| 111 |
答案 3 :(得分:-1)
select t2.prod_id
(select count(*) amount, A.prod_id from A group by prod_id) t1,
(select count(*) amount, B.prod_id from B group by prod_id) t2
where t1.prod_id = t2.prod_id
and t2.amount > t1.amount