我想显示payment_type
点数的所有付款。但是,我只看到一个而我的total
列绝对不对。我必须搞砸JOINs
,但我不知道如何解决它们。我尝试了LEFTs
RIGHTs
等不同的组合,并且不断出现。
我应该看到Tammy
和Terry
。总数目前是正确的。
另外,我在这里查询:
SELECT p.conf,
Concat(g.fname, ' ', g.lname) AS guest,
u.unit_name,
p.card_type,
p.payment_amt,
Sum(p.payment_amt) AS total
FROM payments p,
guests g,
units u,
reservations r
WHERE p.reservation = r.id
AND r.guest = g.id
AND r.unit = u.id
AND p.payment_date = '2013-11-01'
AND p.payment_type = 'credit'
答案 0 :(得分:7)
你可以用子查询做到这一点:
SELECT p.conf,
Concat(g.fname, ' ', g.lname) AS guest,
u.unit_name,
p.card_type,
p.payment_amt,
( SELECT SUM(payment_amt)
FROM payments
WHERE payment_date = p.payment_date
AND payment_type = p.payment_type) AS total
FROM payments p
LEFT JOIN reservations r ON p.reservation = r.id
LEFT JOIN guests g ON r.guest = g.id
LEFT JOIN units u ON r.unit = u.id
WHERE p.payment_date = '2013-11-01'
AND p.payment_type = 'credit'
或者你可以计算之后的总数,并将UNION计算到结果的其余部分:
UNION ALL
SELECT NULL, 'Total', NULL, NULL, SUM(payment_amt)
FROM payments
WHERE payment_date = '2013-11-01'
AND payment_type = 'credit'
Fiddle上的完整SQL
答案 1 :(得分:1)