我们假设我有这四个问题:
SELECT id_cre as credito,
data_eff as data,
'0.00' as incasso,
importo_fatt as spesa
from fatture
WHERE data_eff < '2014-12-31'
UNION
SELECT id_cre as credito,
data_prev as data,
'0.00' as incasso,
importo_fatt as spesa
from fatture
WHERE data_prev >= '2014-12-31'
UNION
SELECT id_cre as credito,
data_prev as data,
importo as incasso,
'0.00' as spesa
from incassi_prev
WHERE data_prev >= '2014-12-31'
UNION
SELECT id_cre as credito,
data_inc as data,
importo_inc as incasso,
'0.00' as spesa
from incassi_row
WHERE data_inc < '2014-12-31'
我用它们来提取代码(信用卡)日期(数据)和金额),可以是收入(incasso)或费用(spesa)。
结果可以创建重复的行(具有相同代码但具有收入的行和具有费用的另一行)。如何重写查询以获得具有相同代码和日期的相同行收入和费用?我想用mysql做这个,因为我已经需要在javascript中遍历生成的数组,以按行重写表(每个代码作为一行,每个月作为一列)。
此外,有没有办法做同样的事情,但考虑同一个月/同一日期的两个不同日期(例如2014-12-20
和2014-12-31
)
谢谢!
答案 0 :(得分:0)
尝试
SELECT credito, data, SUM(incasso) AS incasso, SUM(speca) AS speca
FROM
(
SELECT id_cre AS credito, data_eff AS data, 0.0 AS incasso, importo_fatt AS spesa
FROM fatture
WHERE data_eff < '2014-12-31'
UNION
SELECT id_cre AS credito, data_prev AS data, 0.0 AS incasso, importo_fatt AS spesa
FROM fatture
WHERE data_prev >= '2014-12-31'
UNION
SELECT id_cre AS credito, data_prev AS data, importo AS incasso, 0.0 AS spesa
FROM incassi_prev
WHERE data_prev >= '2014-12-31'
UNION
SELECT id_cre AS credito, data_inc AS data, importo_inc AS incasso, 0.0 AS spesa
FROM incassi_row
WHERE data_inc < '2014-12-31'
) q
GROUP BY credito, data