如果我有一个包含名字,姓氏(复合唯一)和外卖选择的表格,例如
+------+-------+---------+
|First | Last | Food |
+------+-------+---------+
|Bob | Smith | Pizza |
|Bob | Smith | Chips |
|Jim | Smith | Pizza |
|Lisa | Jones | Pizza |
|Lisa | Jones | Chinese |
|Lisa | James | Mexican |
|Eric | White | Chinese |
|Eric | White | Chips |
+------+-------+---------+
我想要的所有行都对应于至少有两种食物偏好的人,其中一种是披萨。即
的结果+------+-------+---------+
|First | Last | Food |
+------+-------+---------+
|Bob | Smith | Pizza |
|Bob | Smith | Chips |
|Lisa | Jones | Pizza |
|Lisa | Jones | Chinese |
+------+-------+---------+
我已尝试过加入...群组......有计数(*)> 1但它并不是我想要的工作。
感谢任何帮助,谢谢。
答案 0 :(得分:1)
您可以首先获取出现多次的名字和姓氏列表:
SELECT first, last
FROM myTable
GROUP BY first, last
HAVING COUNT(*) > 1;
完成后,您可以将其加入原始表格,并确保只选择这些名称:
SELECT m.*
FROM myTable m
JOIN(
SELECT first, last
FROM myTable
GROUP BY first, last
HAVING COUNT(*) > 1) tmp ON tmp.first = m.first AND tmp.last = m.last;
但是,这个问题的问题在于,它并没有验证人们首选的食物中至少有一种是披萨。为此,我们可以在第一个子查询的HAVING子句中添加一个附加条件,以检查一行披萨。我是使用条件聚合完成的:
SELECT m.*
FROM myTable m
JOIN(
SELECT first, last
FROM myTable
GROUP BY first, last
HAVING COUNT(*) > 1 AND SUM(food = 'Pizza') = 1) tmp ON tmp.first = m.first AND tmp.last = m.last;
以下是SQL Fiddle示例。
答案 1 :(得分:1)
另一种方式:SQL Server 2012中的P. +。
SELECT FIRST,LAST,FOOD FROM(
SELECT A.FIRST,A.LAST,B.FOOD,
COUNT(*) OVER (PARTITION BY A.FIRST,A.LAST ORDER BY A.FIRST,A.LAST DESC) AS 'POS'
FROM TEST_FOOD A
INNER JOIN TEST_FOOD B
ON A.FIRST = B.FIRST
AND A.LAST = B.LAST
WHERE A.FOOD = 'PIZZA') TB WHERE POS = 2
在SQL Server 2005+中另一种更标准的方式,第一种方法更快,但受MSSQL版本的限制。
SELECT C.FIRST,C.LAST,C.FOOD FROM
(
SELECT A.FIRST,A.LAST FROM TEST_FOOD A
INNER JOIN TEST_FOOD B
ON A.FIRST = B.FIRST
AND A.LAST = B.LAST
WHERE B.FOOD = 'PIZZA'
GROUP BY A.FIRST,A.LAST
HAVING COUNT(*) = 2
) TB INNER JOIN
TEST_FOOD C
ON TB.FIRST = C.FIRST
AND TB.LAST = C.LAST
答案 2 :(得分:0)
{{1}}
有很多方法可以做到这一点。这只是一种方式。
答案 3 :(得分:0)
select first,last,GROUP_CONCAT(food separator ',')
from people
group by first,last
having count(food) > 1 AND SUM(food = 'Pizza') = 1
小组concat将用逗号分隔的字符串带回食物。
+------+-------+---------------+
|First | Last | Food |
+------+-------+---------------+
|Bob | Smith | Pizza,Chips |
|Lisa | Jones | Pizza,Chinese |
+------+-------+---------------+
答案 4 :(得分:0)
或类似的东西(使用McAdam331'小提琴)...
SELECT DISTINCT y.*
FROM mytable x
JOIN mytable y
ON y.first = x.first
AND y.last = x.last
JOIN mytable z
ON z.first = x.first
AND z.last = x.last
AND z.food <> y.food
WHERE x.food = 'pizza';