mysql – SQL选择跨多个列包含重复数据的行

如果我有一个包含名字,姓氏(复合唯一)和外卖选择的表格,例如

+------+-------+---------+
|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但它不是我想要的工作.

任何帮助表示感谢,谢谢.

最佳答案 另一种方式: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
点赞