如何获得使用mysql排序的格式化日期的不同列表

zpgglvta  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(341)

自从我学习sql已经有好几年了,所以我很难用mysql获得一个格式化日期的清晰列表。我不需要显示我的表,因为我只使用一列datetime

data_vencimento datetime

如果我有2018-10-29,2018-10-29,2018-09-29。它应该被分类为

10/2018
09/2018

请注意,重复的日期被“删除”,并生成了格式化日期的排序列表
这是我的尝试。它正在产生重复的结果。

select distinct(data_vencimento),  date_format( data_vencimento,'%m/%Y' ) as data from (
select data_vencimento from custo_extra_movimento where id_admin
   union
select data_vencimento as data from custo_fixo_movimento where id_admin
   union
select data_vencimento as data from custo_variavel_movimento where id_admin) as tbl order by data_vencimento desc ;
jdzmm42g

jdzmm42g1#

Distinct 不是一个函数;因此,不需要使用带distinct的括号。
然而,您需要月份和年份的不同组合,这样您就可以使用 Group By 相反,使用日期函数 Month() 以及 Year() .
还有,在你的 Union 查询,定义 data 第二个和第三个select查询的别名将不起任何作用。mysql只考虑第一个select查询列名。
请改为执行以下操作:

SELECT 
  YEAR(tbl.data_vencimento) AS year_data, 
  MONTH(tbl.data_vencimento) AS month_data, 
  DATE_FORMAT( MAX(tbl.data_vencimento),'%m/%Y' ) AS data 
FROM (
      select data_vencimento from custo_extra_movimento where id_admin
      union
      select data_vencimento from custo_fixo_movimento where id_admin
      union
      select data_vencimento from custo_variavel_movimento where id_admin
     ) AS tbl 
GROUP BY year_data, month_data 
ORDER BY year_data DESC, month_data DESC
svujldwt

svujldwt2#

我认为这就足够了:

select date_format(data_vencimento, '%m/%Y') as data from custo_extra_movimento where id_admin
union  -- on purpose to remove duplicates
select date_format(data_vencimento, '%m/%Y') as data from custo_fixo_movimento where id_admin
union  -- on purpose to remove duplicates
select date_format(data_vencimento, '%m/%Y') as data from custo_variavel_movimento where id_admin
order by data desc;

老实说,我对订购的逻辑有点不清楚,所以可能会被取消。

相关问题