2

我有一张桌子user(id,name)和一张桌子payments(date,amount,user_id)

我需要一个查询来为每个用户显示上个月的付款总额和付款。

User - totalpayments - monthlypayments

像这样的东西

  1. SELECT id, name from user;
  2. SELECT COUNT(amount) FROM payments WHERE user_id=user.id;
  3. SELECT COUNT(amount) FROM payments WHERE user_id=user.id AND (data<=$timestamptoday AND data>=$timestamp1stday)

是否可以在不进行很多查询的情况下做到这一点?

4

2 回答 2

2

当然,您可以在一个查询中完成。

SELECT
    u.ID,
    u.Name,
    SUM(p.amount),
    SUM(CASE
          WHEN p.date <= '2013-02-01' AND p.date >= '2013-01-01' THEN p.amount
          ELSE 0
        END)
FROM
    Users u
JOIN
    Payments p ON u.ID = p.UserID
GROUP BY
    u.ID,
    u.Name

工作演示

于 2013-09-10T18:41:50.720 回答
0

绝对可以将其作为单个查询执行:

SELECT    user.name, SUM(amount) AS totalpayments, SUM(IF(date <= '$enddate' AND date >= '$startdate'),amount,0) AS monthlypayments
FROM      user LEFT JOIN payments ON user.id = payments.user_id
GROUP BY  user.id
ORDER BY  user.name ASC

请注意,我使用SUM而不是COUNT假设您正在寻找付款的总金额,而不是付款的数量。

于 2013-09-10T18:45:20.400 回答