如何限制每组的行数?

时间:2011-09-16 08:11:43

标签: mysql group-by greatest-n-per-group

我正在使用mysql。我不关心有多少组返回,但如果一个组有超过4个项目我只想要第一个4.如何编写一个只返回4组的语句?作为临时修复,我只是将它们全部返回并在代码中过滤掉它。它仍然非常快,但如果我知道语法会更容易

1 个答案:

答案 0 :(得分:2)

如果我理解你的问题,我相信下面的答案应该大概做你需要的事情(注意:我已经包含了两个测试表及其相关插页作为示例,因为没有提供表结构):

鉴于这些表格和数据:

DROP TABLE IF EXISTS tCustomer;
CREATE TABLE tCustomer (
     customerId INT(11) UNSIGNED NOT NULL auto_increment,
     name       VARCHAR(8),
     PRIMARY KEY (customerId)
) AUTO_INCREMENT=1;

INSERT INTO tCustomer VALUES
(NULL, 'Alex'),
(NULL, 'Bob'),
(NULL, 'Carl')
;

DROP TABLE IF EXISTS tPurchases;
CREATE TABLE tPurchases (
    purchaseId   INT(11) UNSIGNED NOT NULL auto_increment,
    customerId   INT(11) UNSIGNED NOT NULL,
    amount       DECIMAL(9,2),
    purchaseDate DATETIME,
    PRIMARY KEY (purchaseId),
    CONSTRAINT fk_customer FOREIGN KEY (customerId) REFERENCES tCustomer (customerId)
) AUTO_INCREMENT=1;

INSERT INTO tPurchases VALUES
(NULL, 1, 1.00, '2011-01-01 08:00'),
(NULL, 1, 1.01, '2011-01-02 08:00'),
(NULL, 1, 1.02, '2011-01-03 08:00'),
(NULL, 1, 1.03, '2011-01-04 08:00'),
(NULL, 1, 1.04, '2011-01-05 08:00'),
(NULL, 1, 1.05, '2011-01-06 08:00'),
(NULL, 2, 1.01, '2011-01-01 08:00'),
(NULL, 2, 1.02, '2011-01-02 08:00'),
(NULL, 3, 1.01, '2011-01-02 08:00'),
(NULL, 3, 1.02, '2011-01-04 08:00'),
(NULL, 3, 1.03, '2011-01-08 08:00')
;

以下SQL将选择客户返回的购买数据不超过最近的4次购买:

SELECT
    tC.customerId, tC.name, tP.purchaseDate, tP.amount, COUNT(tPNewer.customerId) newerCt
FROM
                    tCustomer  tC
    INNER JOIN      tPurchases tP      ON tC.customerId = tP.customerId
    LEFT OUTER JOIN tPurchases tPNewer ON tP.customerId = tPNewer.customerId AND tPNewer.purchaseId > tP.purchaseId
GROUP BY
    tC.customerId,
    tC.name,
     tP.purchaseDate,
     tP.amount
HAVING
    newerCt < 4 -- Ignore rows that have more than 3 newer records
ORDER BY
     tC.customerId,
     tP.purchaseDate desc
;

以下是此选择的结果输出(请注意,Alex的最旧交易不存在):

+------------+------+---------------------+--------+---------+
| customerId | name | purchaseDate        | amount | newerCt |
+------------+------+---------------------+--------+---------+
|          1 | Alex | 2011-01-06 08:00:00 |   1.05 |       0 |
|          1 | Alex | 2011-01-05 08:00:00 |   1.04 |       1 |
|          1 | Alex | 2011-01-04 08:00:00 |   1.03 |       2 |
|          1 | Alex | 2011-01-03 08:00:00 |   1.02 |       3 |
|          2 | Bob  | 2011-01-02 08:00:00 |   1.02 |       0 |
|          2 | Bob  | 2011-01-01 08:00:00 |   1.01 |       1 |
|          3 | Carl | 2011-01-08 08:00:00 |   1.03 |       0 |
|          3 | Carl | 2011-01-04 08:00:00 |   1.02 |       1 |
|          3 | Carl | 2011-01-02 08:00:00 |   1.01 |       2 |
+------------+------+---------------------+--------+---------+