多聚合的sql查询函数

时间:2014-11-26 08:07:06

标签: mysql sql

我有以下查询:

SELECT u.username, t.pack_id, COUNT( t.id ) transaction_count
FROM  `transaction` t
INNER JOIN  `user` u ON t.customer_id = u.id
GROUP BY (
t.customer_id
)
HAVING transaction_count >1

我正在尝试获取具有transaction_count>的所有用户的用户名和交易。 1 并且创建的第一个交易的数量为3,我希望获得这样的列表:

username:
    transaction1
    transaction2

username2:
    transaction3
    transaction4
    transaction5

这甚至可能吗?我的事务表看起来像这样:

enter image description here

这是我的用户表:

enter image description here

1 个答案:

答案 0 :(得分:0)

您无法从MySQL获得类似的输出,最接近的可能是:

user1 trans1
user1 trans2
user1 trans3
user1 trans4
user2 trans1
user2 trans2
user2 trans3

要做到这一点,就像你一样简单inner join。但是,要应用您想要的这两个条件,它会变得有点复杂

SELECT ux.*,tx.* FROM
(
  SELECT u.*,count(t1.id) as transaction_count FROM users u
  INNER JOIN transaction t1 ON t1.customer_id = u.id
  INNER JOIN (
    SELECT s1.customer_id,MIN(s1.created) as min_date
    FROM transaction s1
    GROUP BY s1.customer_id
  ) t2 ON t2.customer_id = u.id 
  INNER JOIN transaction t3 ON t3.customer_id = u.id AND t3.created = t2.min_date AND t3.quatity>3
  GROUP BY u.id
  HAVING count(t1.id)>3
) ux
INNER JOIN transaction tx ON tx.customer_id = ux.id
ORDER BY ux.id,tx.id

简短说明:

子查询t2中的

事务s1用于查找每个用户的第一个事务的日期

事务t3用于在第一笔交易中按数量过滤用户(感谢t2.min_date)

事务t1用于计算每个用户的事务(并在having子句中过滤3个或更少的事务)

子查询ux包含符合这两个条件的用户

事务tx最终将每个用户的事务添加到输出


编辑:我的错误,我认为你想要transaction_count> 3条件,但我看到你键入了transaction_count> 1;没什么大不了的,查询只是让一行更简单,那个条件是由INNER JOIN t3处理的(INNER JOIN赢得了没有匹配事务的用户),因此我将使用事务t1将事务计入transactions_count列

SELECT ux.*,tx.* FROM
(
  SELECT u.*,count(t1.id) as transaction_count FROM users u
  INNER JOIN transaction t1 ON t1.customer_id = u.id
  INNER JOIN (
    SELECT s1.customer_id,MIN(s1.created) as min_date
    FROM transaction s1
    GROUP BY s1.customer_id
  ) t2 ON t2.customer_id = u.id 
  INNER JOIN transaction t3 ON t3.customer_id = u.id AND t3.created = t2.min_date AND t3.quatity>3
  GROUP BY u.id
) ux
INNER JOIN transaction tx ON tx.customer_id = ux.id
ORDER BY ux.id,tx.id