0

我有这个数据的表:

 1. John | seafood pizza 
 2. Mike | pepperoni pizza 
 3. Mike | pepperoni pizza
 4. John | original pizza 
 5. Mike | original pizza 
 6. John | seafood pizza
 7. John | pepperoni pizza

……

我怎样才能写一个查询给我这样的结果:

John | seafood pizza
Mike | pepperoni pizza

如果客户有多个披萨的数量相同,则结果可能是任何披萨的名称。

4

3 回答 3

2

让我们一步一步来

以下查询将为您提供每个客户订购每种披萨的次数

SELECT name, pizza, COUNT(*) AS cnt 
FROM yourTable 
GROUP BY name, pizza

那么我们如何从中获得最常订购的披萨呢?我们首先要知道,每个客户点的比萨饼数量最多是多少

SELECT name, MAX(cnt) AS cnt FROM (
  SELECT name, pizza, COUNT(*) AS cnt 
  FROM yourTable 
  GROUP BY name, pizza
) AS subquery GROUP BY name

然后使用此数字选择实际的披萨名称

SELECT name, pizza, COUNT(*) AS cnt 
FROM yourTable AS t
CROSS JOIN (
  SELECT name, MAX(cnt) AS cnt FROM (
    SELECT name, pizza, COUNT(*) AS cnt 
    FROM yourTable 
    GROUP BY name, pizza
  ) AS subquery GROUP BY name
) AS sq
USING(name,cnt)
GROUP BY name, pizza
于 2013-03-01T09:45:00.633 回答
0

我将按用户和比萨饼对计数进行分组,然后将其用作查找分组最大值的查询的数据源(使用 max concat 技巧)。这并不难:

SELECT user, SUBSTRING(MAX(CONCAT(LPAD(freq, 6, '0'),pizza)),7)
FROM
(SELECT user, pizza, COUNT(*) AS freq
FROM user_likes
GROUP BY user, pizza) ilv
GROUP BY user
于 2013-03-01T09:42:52.500 回答
-1

让我们有一个简单的解决方案:首先,我们有两列,名称和食物。您可以轻松列出最喜欢的顾客的食物:

CREATE TEMPORARY TABLE tbltemp AS (
SELECT name, food, COUNT( * ) c
FROM food
GROUP BY name, food
);

现在我们按数量计算了所有食物。然后你可以按 count descending 来排序:

SELECT *
FROM tbltemp
ORDER BY c DESC

现在您有一个描述您的客户最喜欢的列表。

更新 :

而不是第二个查询,替换这个:

SELECT tbl1 . *
FROM (

SELECT name, food, COUNT( * ) c
FROM food
GROUP BY name, food
) AS tbl1, (

SELECT name, food, COUNT( * ) c
FROM food
GROUP BY name, food
) AS tbl2
WHERE tbl1.c = tbl2.c
AND tbl2.name = tbl1.name
AND tbl2.food = tbl1.food
AND tbl1.c = (
SELECT c
FROM tbltemp
ORDER BY c DESC
LIMIT 1 )

此查询结果是您的问题目标。

于 2013-03-01T11:21:24.413 回答