我的数据格式如下:
date
(mm / dd / yyyy),desc
(详情desc),category
(a,b,c),tran_type
(借记卡,赠送), amount spent
(金额)。
我想以下列格式获取数据:
category || tran_type || Jan_total || feb_total || mar_total
A || debit || $101 || $201 || $302
A || credit || $500 || $600 || $200
答案 0 :(得分:9)
此查询应该为您提供所需的结果。
SELECT category
,tran_type
,SUM(IF(month(date) = 1,ABS(amount),0)) as jan_total
,SUM(IF(month(date) = 2,ABS(amount),0)) as feb_total
,SUM(IF(month(date) = 3,ABS(amount),0)) as mar_total
,SUM(IF(month(date) = 4,ABS(amount),0)) as apr_total
,SUM(IF(month(date) = 5,ABS(amount),0)) as may_total
,SUM(IF(month(date) = 6,ABS(amount),0)) as jun_total
,SUM(IF(month(date) = 7,ABS(amount),0)) as jul_total
,SUM(IF(month(date) = 8,ABS(amount),0)) as aug_total
,SUM(IF(month(date) = 9,ABS(amount),0)) as sep_total
,SUM(IF(month(date) = 10,ABS(amount),0)) as okt_total
,SUM(IF(month(date) = 11,ABS(amount),0)) as nov_total
,SUM(IF(month(date) = 12,ABS(amount),0)) as dec_total
FROM transactions
WHERE YEAR(date) = '2011'
GROUP BY category, tran_type
如果您不想遇到麻烦,请不要忘记过滤年份。
答案 1 :(得分:0)
那几年呢?您是否希望Janury专栏在2011年1月添加2011年1月的交易?
我假设您需要单独添加Year列或为其使用WHERE子句,因此包含该示例的两个选项:
基本上你需要生成12个子查询才能实现这一点,而SQL看起来会很混乱,并不是实现这个目标的常用方法:
SELECT category, YEAR(date), tran_type,
(SELECT SUM(amounts) FROM TableName s1 WHERE YEAR(t.date)=YEAR(s1.date) AND MONTH(s1.date)=1 AND t.category=s1.category AND t.tran_type=s1.tran_type) AS 'Jan_Total',
(SELECT SUM(amounts) FROM TableName s2 WHERE YEAR(t.date)=YEAR(s2.date) AND MONTH(s2.date)=2 AND t.category=s2.category AND t.tran_type=s2.tran_type) AS 'Feb_Total',
....REPEAT ABOVE 2 LINES FOR EACH MONTH
FROM TableName t
WHERE t.date>'2011-01-01'
GROUP BY t.category, YEAR(t.date), t.tran_type;
如上所述,上述内容并不完全优雅,更好的解决方案是使用以下SQL并将表示层中的数据格式化为用户:
SELECT category, YEAR(date), MONTH(date), tran_type, SUM(amounts)
FROM TableName
GROUP BY TableName;
希望有所帮助。
答案 2 :(得分:0)
单个月(2011年1月)您可以使用:
SELECT category, tran_type, SUM(amount_spent) AS total FROM myTable WHERE date>="2011-01-01" AND date<"2011-02-01" GROUP BY category, tran_type;
假设您的索引至少为date
,那么这应该相当快。更好的索引是(date, category, tran_type)
,因为这也有助于分组。
如果您希望以您描述的格式组合多个月,您可以将这些查询组合为子查询,例如:
SELECT jan.category, jan.tran_type, jan.total, feb.total FROM
(SELECT category, tran_type, SUM(amount_spent) AS total FROM myTable WHERE date>="2011-01-01" AND date<"2011-02-01" GROUP BY category, tran_type) AS jan,
(SELECT category, tran_type, SUM(amount_spent) AS total FROM myTable WHERE date>="2011-02-01" AND date<"2011-03-01" GROUP BY category, tran_type) AS feb
WHERE jan.category = feb.category
AND jan.tran_type = feb.tran_type;
虽然我怀疑获取您想要的数据的最简单方法(虽然不是非常有效且不是您所描述的格式),但是:
SELECT category, tran_type, MONTH(date) AS theMonth, SUM(amount_spent) AS total FROM myTable WHERE date>="2011-01-01" AND date<"2012-01-01" GROUP BY category, tran_type, theMonth;
MONTH()
函数的使用远非最佳,但如果您不运行通常可能的查询。