MySQL - 分组和总计,但返回每个组中的所有行

时间:2015-01-26 20:22:03

标签: mysql

我试图编写一个查询,查询每次在特定日期范围内我的表中出现同一个人。然后它将这个人分组并将他们的支出总计为特定范围。如果他们的消费习惯大于X金额,则在指定的日期范围之间返回此人的每一行。不仅仅是分组总金额。这就是我到目前为止所做的:

SELECT member_id, 
SUM(amount) AS total 
FROM `sold_items` 
GROUP BY member_id 
HAVING total > 50

这是检索花费超过50美元但不是每一行的正确总成员和回归成员。只是每个成员及其总数的总和。我目前正在查询整个表格,但我还没有添加日期范围。

5 个答案:

答案 0 :(得分:20)

JOIN这个带有原始表的子查询:

SELECT si1.*
FROM sold_items AS si1
JOIN (SELECT member_id
      FROM sold_items
      GROUP BY member_id
      HAVING SUM(amount) > 50) AS si2
ON si1.member_id = si2.member_id

一般规则是子查询按其选择的相同列进行分组,然后使用相同的列将其与原始查询连接。

答案 1 :(得分:1)

SELECT member_id, amount
FROM sold_items si
INNER JOIN (SELECT member_id, 
SUM(amount) AS total 
FROM `sold_items` 
GROUP BY member_id 
HAVING total > 50) spenders USING (member_id)

您已构建的查询可用作要加入的临时表。如果member_id不是表上的索引,那么随着比例的增加,这将变得很慢。 单词spenders是一个表别名,您可以使用任何有效的别名。

答案 2 :(得分:0)

有一些语法可以获得您正在查找的结果,这里有一个使用内部联接来确保返回的所有行在group by返回的列表中都有一个member_id,并且每个行重复一次某位成员有:

SELECT si.*, gb.total from sold_items as si, (SELECT member_id as mid, 
SUM(amount) AS total 
FROM `sold_items` 
GROUP BY member_id 
HAVING total > 50) as gb where gb.mid=si.member_id;

答案 3 :(得分:0)

我认为这可能有所帮助:

SELECT 
    member_id, 
    SUM(amount) AS amount_value,
    'TOTAL' as amount_type
FROM 
    `sold_items` 
GROUP BY 
    member_id 
HAVING 
    SUM(amount) > 50

UNION ALL

SELECT 
    member_id,
    amount AS amount_value,
    'DETAILED' as amount_type
FROM 
    `sold_items` 
    INNER JOIN
    (
        SELECT 
            A.member_id, 
            SUM(amount) AS total 
        FROM 
            `sold_items` A 
        GROUP BY 
            member_id 
        HAVING 
            total <= 50
    ) AS A
    ON `sold_items`.member_id = A.member_id 

上述查询的结果应如下所示:

member_id     amount_value    amount_type
==========================================
1             55              TOTAL
2             10              DETAILED
2             15              DETAILED
2             10              DETAILED

因此列amount_type将区分两个特定成员组

答案 4 :(得分:0)

您可以使用EXISTS作为替代方式执行子查询:

select *
from sold_items t1
where exists (
    select * from sold_items t2
    where t1.member_id=t2.member_id
    group by member_id
    having sum(amount)>50
)

参考:http://dev.mysql.com/doc/refman/5.7/en/exists-and-not-exists-subqueries.html