根据年份和月份获取数据

时间:2019-02-12 13:55:16

标签: mysql sql

我有一张表,里面有一些数据:month_number(int),year(int)。

我想获取基于2年零2个月的数据

SELECT
  tt.year AS raw_annee,
  tt.month AS raw_mois,
  tt.product AS raw_produit,
  tt.quantity_product AS tonnes_prod,
  tt.quantity_n AS raw_tonnes_N,
  tt.quantity_p AS raw_tonnes_P,
  tt.quantity_k AS raw_tonnes_K
FROM test_test as tt    
  WHERE (tt.year >= 2014 AND tt.month_number >= 5)
  AND (tt.year <= 2018 AND tt.month_number <= 5)
  ORDER BY tt.year desc, tt.month_number desc;

但是我只获得2014年至2018年5月的数据,但我的想法是从2014年5月---> 2018年5月获得数据

能帮我吗?

4 个答案:

答案 0 :(得分:7)

您只想比较第一年和最后一年的月份:

  WHERE (tt.year > 2014 AND tt.year < 2018)
    or  (tt.year = 2014 AND tt.month_number >= 5)
    or  (tt.year = 2018 AND tt.month_number <= 5)

或者:

WHERE (tt.year * 100 + tt.month_number >= 201405)
  AND (tt.year * 100 + tt.month_number <= 201805)

或者,MySQL不支持:

WHERE (tt.year, tt.month_number) between (2014,5) and (2018,5)

Raymond Nijland适应MySQL:

WHERE (tt.year, tt.month_number) >= (2014,5) AND (tt.year, tt.month_number) <= (2018,5)

答案 1 :(得分:0)

我认为您需要的是以下内容:

SELECT
  tt.year AS raw_annee,
  tt.month AS raw_mois,
  tt.product AS raw_produit,
  tt.quantity_product AS tonnes_prod,
  tt.quantity_n AS raw_tonnes_N,
  tt.quantity_p AS raw_tonnes_P,
  tt.quantity_k AS raw_tonnes_K
FROM test_test as tt    
  WHERE (tt.year > 2014 AND tt.year < 2018) OR  (tt.year = 2014 AND tt.month_number >= 5) OR  (tt.year = 2018 AND tt.month_number <= 5)
  ORDER BY tt.year desc, tt.month_number desc;

只需在您的where语句中对逻辑进行修改

答案 2 :(得分:0)

以其他日期表示日期:

STR_TO_DATE(CONCAT(tt.year,'-',tt.month_number,'-',01), '%Y-%m-%d') 

示例:

WHERE STR_TO_DATE(CONCAT(tt.year,'-',tt.month_number,'-',01), '%Y-%m-%d')  >= '01-05-2014' AND  STR_TO_DATE(CONCAT(tt.year,'-',tt.month_number,'-',01), '%Y-%m-%d') <= '01-05-2018'

Create date from day, month, year fields in MySQL

答案 3 :(得分:0)

您始终可以将比较作为日期进行:

where date(concat_ws('-', tt.year, tt.month_number)) between '2014-05-01' and '2018-05-01

如果需要进行日期比较,那么我建议您将值存储为日期。