我的表Kot_items
中有一个日期字段。如何在数据库中提取月份名称(如果不是当月)?
select distinct month(Tran_date) as mon
from Kot_items
数据库中的数据
MON monthname
1 jan
2 feb
3 mar
例外结果
MON monthname
1 jan
2 feb
3 mar
4 Apr
5 mar
6 june
7 july
8 Aug
9 Sep
10 Oct
11 nov
12 Dec
更新帖子::
形成此查询::
选择年份(tran_date)作为年份, QUARTER(tran_date)为季度数, 月(tran_date)为星期一 来自KOT_Items
yearnumber quarternumber mon
2014 2 4
2014 2 4
2014 2 4
2014 2 4
2014 2 4
2014 2 4
2014 2 4
2014 2 4
2014 2 4
2014 2 4
2014 2 4
2014 2 4
2014 2 4
喜欢的结果
yearnumber quarternumber mon
2014 1 1
2014 1 2
2014 1 3
2014 2 3
2014 2 4
2014 2 5
2014 3 6
2014 3 7
2014 3 8
2014 4 9
2014 4 10
2014 4 11
2014 4 12
答案 0 :(得分:0)
您可以使用:
SELECT MONTH(Trans_date) as mon, MONTHNAME(Tran_date) as monthname FROM Kot_items ;
所有月份
SELECT 1 as mon, 'January' AS
MONTH
UNION SELECT 2 as mon 'February' AS
MONTH
UNION SELECT 3 as mon 'March' AS
MONTH
UNION SELECT 4 as mon 'April' AS
MONTH
UNION SELECT 5 as mon 'May' AS
MONTH
UNION SELECT 6 as mon 'June' AS
MONTH
UNION SELECT 7 as mon 'July' AS
MONTH
UNION SELECT 8 as mon 'August' AS
MONTH
UNION SELECT 9 as mon 'September' AS
MONTH
UNION SELECT 10 as mon 'October' AS
MONTH
UNION SELECT 11 as mon 'November' AS
MONTH
UNION SELECT 12 as mon 'December' AS
MONTH
) AS m
最简单的方法是创建一个单独的表,并加入您当前拥有的表(Kot_items
)
From here
答案 1 :(得分:0)
尝试SELECT MONTHNAME(datefield) as monthname FROM tablename
答案 2 :(得分:0)
一种方法是创建一个包含所有月份的表。然后,您可以在此表和事务表之间使用外部联接。
CREATE TABLE months (mon INT, monthname CHAR(3)) AS
SELECT 1, 'Jan'
UNION
SELECT 2, 'Feb'
UNION
SELECT 3, 'Mar'
...
SELECT 12, 'Dec'
如果你不能这样做,你可以使用UNION子查询:
SELECT * FROM (
SELECT 1 AS mon, 'Jan' AS monthname
UNION
SELECT 2, 'Feb'
UNION
SELECT 3, 'Mar'
...
SELECT 12, 'Dec') AS months
LEFT JOIN Kot_items AS i ON months.mon = MONTH(i.tran_date)
然后可以将其与您的交易表结合使用。
对于年,季度和月份,请执行:
SELECT YEAR(NOW()) AS yearnumber, 1 as quarternumber, 1 as mon
UNION ALL
SELECT YEAR(NOW()), 1, 2
UNION ALL
SELECT YEAR(NOW()), 1, 3
UNION ALL
SELECT YEAR(NOW()), 2, 4
UNION ALL
SELECT YEAR(NOW()), 2, 5
UNION ALL
SELECT YEAR(NOW()), 2, 6
UNION ALL
SELECT YEAR(NOW()), 3, 7
UNION ALL
SELECT YEAR(NOW()), 3, 8
UNION ALL
SELECT YEAR(NOW()), 3, 9
UNION ALL
SELECT YEAR(NOW()), 4, 10
UNION ALL
SELECT YEAR(NOW()), 4, 11
UNION ALL
SELECT YEAR(NOW()), 4, 12
如果您使用我上面显示的months
表格,您只需在表格中添加quarternumber
列即可。要为当前年份制作表格,您可以使用如下查询:
SELECT YEAR(NOW()), quarternumber, mon
FROM months
答案 3 :(得分:0)
SELECT m.mon, m.month
FROM (
SELECT 1 as mon, 'Jan' as month
UNION
SELECT 2 as mon, 'Feb' as month
UNION
SELECT 1 as mon, 'Mar' as month
UNION
SELECT 1 as mon, 'Apr' as month
UNION
SELECT 1 as mon, 'May' as month
UNION
SELECT 1 as mon, 'Jun' as month
UNION
SELECT 1 as mon, 'Jul' as month
UNION
SELECT 1 as mon, 'Aug' as month
UNION
SELECT 1 as mon, 'Sep' as month
UNION
SELECT 1 as mon, 'Oct' as month
UNION
SELECT 1 as mon, 'Nov' as month
UNION
SELECT 1 as mon, 'Dec' as month
) AS m
LEFT JOIN Kot_items k ON m.month = k.month(Tran_date)