使用 SQL (MySQL) 从日期列中获取所有唯一年份
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6841230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get all unique years from a date column using SQL (MySQL)
提问by tvgemert
I have a MySQL table with a datetime column named 'created' which contains the date and time the record was inserted. This table has about 30 records right now. I want to get all occuring years (unique, not per record) from this table. Is there a way to do this using a MySQL query?
我有一个 MySQL 表,其中包含一个名为“created”的日期时间列,其中包含插入记录的日期和时间。这个表现在有大约 30 条记录。我想从这个表中获取所有发生的年份(唯一的,不是每条记录)。有没有办法使用 MySQL 查询来做到这一点?
回答by Dan Grossman
SELECT DISTINCT YEAR(created) FROM table
回答by Sukumar
Something on these lines should work (Warning: untested code ahead)
这些行上的东西应该可以工作(警告:前面未经测试的代码)
select year(created) as year, count(*) as count from table_name group by year
This will also give number of records for each year.
这也将给出每年的记录数。
回答by Quasdunk
SELECT EXTRACT(year from created) as year
FROM your_table
GROUP BY year
should work :)
应该管用 :)
回答by J Bettis
SELECT DISTINCT YEAR(Date) AS MYR FROM YOUR_DBF_HERE ORDER BY MYR
SELECT DISTINCT YEAR(Date) AS MYR FROM YOUR_DBF_HERE ORDER BY MYR
回答by Cristian Girlea
tableName::whereNotNull('columnName')->distinct()->get([DB::raw('YEAR(columnName) as year')]);
This is select distinct year from a date column in laravel. I added whereNotNullbecause in my database the date is not a requirement.
这是从laravel的日期列中选择不同的年份。我添加了whereNotNull因为在我的数据库中日期不是必需的。
回答by Sukanya1991
Select
EXTRACT(year from your_column_name) as MYEAR from your_table_name
group by EXTRACT(year from your_column_name)
The above worked for me...
以上对我有用...