我有这个问题:
SELECT COUNT(*), SUBSTR(datetime_acc, 1, 10), type_acc FROM payment_acc WHERE type_acc LIKE '%monthly%' GROUP BY SUBSTR(datetime_acc, 1, 10), type_acc ORDER BY datetime_acc, type_acc
count date type_acc ------ ---------- --------------- 4 2011-01-20 monthly payment 3 2011-01-20 failed monthly 5 2011-01-21 monthly payment 10 2011-01-22 failed monthly 11 2011-01-22 monthly payment 1 2011-01-23 monthly payment 4 2011-01-24 monthly payment 1 2011-01-24 failed monthly 6 2011-01-25 failed monthly 6 2011-01-25 monthly payment 16 2011-01-26 failed monthly 10 2011-01-26 monthly payment
但是我试图让失败并在不同的列中一起传递
success failed date ------- ------ ---------- 4 3 2011-01-20 5 10 2011-01-21 11 NULL 2011-01-22 1 NULL 2011-01-23 4 1 2011-01-24 6 6 2011-01-25 10 16 2011-01-26
任何线索?
答案 0 :(得分:1)
将现有查询放在视图中,然后按如下方式查询视图:
SELECT
T1.date,
T2.count AS success_count,
T3.count AS failed_count
FROM yourview T1
LEFT JOIN yourview T2 ON T1.date = T2.date AND T2.type_acc = 'monthly payment'
LEFT JOIN yourview T3 ON T1.date = T3.date AND T3.type_acc = 'failed monthly'
GROUP BY T1.date
结果:
date success_count failed_count
2011-01-20 4 3
2011-01-21 5 NULL
2011-01-22 11 10
2011-01-23 1 NULL
2011-01-24 4 1
2011-01-25 6 6
2011-01-26 10 16
答案 1 :(得分:0)
子查询是我认为这是可能的唯一方式。它确实意味着很多派生表。使用EXPLAIN选项查看它有多丑。
SELECT b.intSuccess,c.intFailed,a.dateThis 从 (SELECT DATE(datetime_acc)AS dateThis FROM payment_acc)a LEFT JOIN(SELECT COUNT(*)AS intFailed,DATE(datetime_acc)AS dateThis FROM payment_acc WHERE type_acc LIKE“%failed%”AND type_acc LIKE“%monthly%”GROUP BY DATE(datetime_acc))b ON b.dateThis = a。 dateThis LEFT JOIN(SELECT COUNT(*)AS intSuccess,DATE(datetime_acc)AS dateThis FROM payment_acc
WHERE type_acc NOT LIKE“%failed%”AND type_acc LIKE“%monthly%”GROUP BY(datetime_acc))c ON c.dateThis = a.dateThis ORDER BY a.dateThis;