如何在Mysql中编写查询

时间:2015-07-02 08:36:31

标签: mysql

我有2个tables.ms_expese和track_expense。使用此表生成一个事实表 我想要ms_expense中的expense_name,来自track_expense的expense_amount。

我想根据日期得到特定fee_name的expense_amount之和。日期顺序为1,2 ... 12作为月份id

            SELECT DATE_Format(a.date,'%b') as month_id,b.expense_name AS  expense_type, sum(a.expense_amount) AS expense_amount FROM ms_expense b JOIN track_expense a on a.`expense_id`=b.`expense_id` group by DATE_Format(a.date,'%b') 

如何将月份ID按1,2,... 12和我的日期格式y-m-d的顺序排列 我得到apr,aug等月份,但我需要jan为1,feb as 2

我有25个费用(费用名称)。在这个查询中我只得到了第一笔费用的总费用。我想要每个月所有费用的总费用

1 个答案:

答案 0 :(得分:2)

CREATE TABLE fact AS 
(<your select query>)

您的选择查询可以采用以下格式

SELECT MONTH(date)as month_id,expense_name,sum(expense_amount) 
FROM ms_expense JOIN track_expense using (expense_id) 
group by expense_name,MONTH(date)