MySQL:多个分组

时间:2009-03-25 12:42:29

标签: sql mysql group-by

所以我有一个名为 items 的示例表,其中包含以下列:

  • item_id (int)
  • person_id (int)
  • item_name (varchar)
  • item_type (varchar) - 示例:“news”,“event”,“document”
  • item_date (日期时间)

...以及包含以下列的表:“person_id”,“person_name”。

我希望在每个item_type 的给定时间段内显示前2个提交者的列表(+提交的项目的COUNT())。这基本上是我希望MySQL输出的样子:

person_name  | item_type | item_count

Steve Jobs   | document  | 11
Bill Gates   | document  | 6
John Doe     | event     | 4
John Smith   | event     | 2
Bill Jones   | news      | 24
Bill Nye     | news      | 21

如果不为每个item_type单独查询,这怎么可能?提前谢谢!

3 个答案:

答案 0 :(得分:2)

SELECT  item_type, person_name, item_count
FROM    (
        SELECT  item_type, person_name, item_count,
                @r := IFNULL(@r, 0) + 1 AS rc,
                CASE WHEN @_item_type IS NULL OR @_item_type <> item_type THEN @r := 0 ELSE 1 END,
                @_item_type := item_type,
        FROM    (
                SELECT  @r := 0,
                        @_item_type := NULL
                ) vars,
                (
                SELECT  item_type, person_name, COUNT(*) AS item_count
                FROM    items
                GROUP BY
                        item_type, person_name
                ORDER BY
                        item_type, person_name, item_count DESC
                ) vo
        ) voi
WHERE   rc < 3

答案 1 :(得分:1)

我认为应该这样做:

SELECT person_name,item_type,count(item_id) AS item_count
FROM person
LEFT JOIN items USING person_id
GROUP BY person_id

“item_type”列虽然很狡猾,但每行代表多个项目,而您只显示其中一项的item_type。你可以用“GROUP_CONCAT”列出所有这些,这很有趣。

答案 2 :(得分:1)

这样的事情应该有效:

SELECT
  p.person_name, i.item_type, COUNT(1) AS item_count
FROM
  person p
  LEFT JOIN item i
    ON p.person_id = i.person_id
GROUP BY
  p.person_id,
  i.item_type
HAVING
  COUNT(1) >= (
    SELECT
      COUNT(1)
    FROM
      item i2
    WHERE
      i2.item_type = i.item_type
    GROUP BY
      i2.person_id
    LIMIT 1,1
  )