所以我有一个衣柜桌子,上面记录着拥有彩色衬衫的人。像这样,
================================
| People | Shirt |
================================
| Peter | red |
| Peter | green |
| Peter | blue |
| Peter | blue |
| John | red |
| John | green |
| Kenny | yellow |
| Kenny | yellow |
| Kenny | green |
| Sam | yellow |
| Sam | green |
| Sam | purple |
| Chris | red |
| Chris | red |
================================
我需要帮助查询一个人有多少衬衫,只有红色衬衫。以下查询很接近,但不是我想要的。
Select people, count(shirt) from Wardrobe where shirt='red' group by people.
结果是
===========================
| People | count(shirt) |
===========================
| Peter | 1 |
| John | 1 |
| Chris | 2 |
==========================
我想从查询中得到的结果会给我这个
===========================
| People | count(shirt) |
===========================
| Chris | 2 |
==========================
+++++++++++++++++++++++++++++++++++++++
更新
如果我碰巧加入多个表格以及数百万的总记录,哪种技术会更好,效率更高?
答案 0 :(得分:1)
获取一个人的红色衬衫总数,将其与衬衫总数进行比较,因此您只返回相同的行。
SELECT People, SUM(Shirt = "red") AS redcount
FROM Wardrobe
GROUP BY People
HAVING redcount = COUNT(*)
或者只是排除任何有红色衬衫的人:
SELECT People, COUNT(*) AS redcount
FROM Wardrobe
WHERE People NOT IN (
SELECT People
FROM Wardrobe
WHERE Shirt != "red")
GROUP BY People
答案 1 :(得分:1)
更长的版本:)
select w.people, w.cnt
from (
Select people,count(shirt) as cnt
from Wardrobe
where shirt = 'red'
group by people) w
join (
select people, count(shirt) as d_cnt
from Wardrobe
group by people) t
on w.people = t.people and w.cnt = t.d_cnt
答案 2 :(得分:-2)
你必须使用子查询。
SELECT People,COUNT(*)AS total FROM(SELECT DISTINCT * FROM Wardrobe WHERE shirt =' red' GROUP BY People);