嵌套查询的菜鸟问题。这个 SQL 查询有一点问题。请帮忙。尝试对同一个表中的 2 个字段进行计数,并按月、年分组。查询在新字段和续订字段中返回相同的结果。
SELECT MONTH(p.created_at) as Month, YEAR(p.created_at) as Year,
(SELECT COUNT(p.id) FROM payments p
INNER JOIN carts c ON c.payment_id = p.id
INNER JOIN cart_items ci on ci.cart_id = c.id
WHERE ci.item_id = 8) as 'New',
(SELECT COUNT(p.id) FROM payments p
INNER JOIN carts c ON c.payment_id = p.id
INNER JOIN cart_items ci on ci.cart_id = c.id
WHERE ci.item_id = 13) as 'Renewal',
FROM payments p
GROUP BY month, year
谢谢您的帮助!
查询示例
Month Year New Renewal
1 2010 1169 556
1 2011 1169 556
1 2012 1169 556
2 2010 1169 556
2 2011 1169 556