简体   繁体   English

SQL查询以选择年份在两个日期之间的行

[英]SQL query to select rows where the year is between two dates

Given a Table with from_date date and a to_date date column, I want to select all sets of data where an year, for example 2007, is the year of one of the dates or both or is in between the two dates. 给定具有from_date date和to_date date列的表,我想选择所有数据集,其中年份(例如2007)是其中一个日期的年份,或者是两个日期之间或两个日期之间的年份。

How can i achieve this using mySQL? 如何使用MySQL实现此目的?

Table: 表:

create Table Articleprice
(`ArtikelpreisNR` int, `ArtikelNR` int, `from_Date` date, `to_date` date, `price` int);

Example Testdata 示例测试数据

insert into Articleprice
(`ArtikelPreisNR`, `ArtikelNR`,`from_Date`, `to_Date` ,`price`)

values (1, 1, '2006-7-04', '2008-7-04', 10);

SQL: This is returning only the ones, when from_date and to_date = 2007 SQL:当from_date和to_date = 2007时,这仅返回那些

SELECT
MIN(price)
FROM  Articleprice
WHERE Articleprice.from_Date >= '2007/01/01' and Articleprice.to_Date <= '2007/12/31';

What do I need to do in order to solve my Case? 为了解决我的问题,我需要做什么?

假设日期实际上是日期而不是字符串,则需要在查询中使用正确的日期格式:YYYY-MM-DD而不是YYY / MM / DD:

WHERE Articleprice.from_Date >= '2007-01-01' and Articleprice.to_Date <= '2007-12-31';

First you build complete dates using the year. 首先,您使用年份建立完整的日期。 For 2007, the dates would be 2007-01-01 and 2007-12-31 (assuming that end dates are inclusive). 2007年,该日期为2007-01-012007-12-31 (假设结束日期包含在内)。

Next you use overlapping dates query to find all rows that (i) end inside (ii) start inside (iii) contain or (iv) contained within the year 2007. The query is simply: 接下来,您使用重叠日期查询来查找(i)在(ii)内部开始(iii)在(iii)中包含或(iv)在2007年之内的所有行。该查询很简单:

SELECT * FROM Articleprice
WHERE '2007-12-31' >= from_Date AND to_date > '2007-01-01'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM