如何选择不重复的日期间隔?

时间:2019-03-16 08:20:14

标签: sql database

我的产品表

year
2014
2013
2012
2011
2010
2009
2008
2007
2006
2005
2004
2003
2002
2001
2000

我的查询

SELECT dt||'-'||dt1 
FROM
(SELECT year as dt, year+4 as dt1
FROM
products 
GROUP BY year);

我的输出

2000-2004
2001-2005
2002-2006
2003-2007
2004-2008
2005-2009
2006-2010
2007-2011
2008-2012
2009-2013
2010-2014
2011-2015
2012-2016
2013-2017
2014-2018

预期结果

2000-2004 
2005-2009 
2010-2014

我不知道产生该日期间隔的任何线索。 查询的任何提示和建议都会有很大帮助。 谢谢

3 个答案:

答案 0 :(得分:3)

您可以使用SQLite ROW_NUMBER创建一个行号列,并使用此列来计算要检索的记录:

SELECT t.year ||'-'|| (t.year + 4)
FROM (
    SELECT  *, Row_Number() OVER(ORDER BY year) AS RowNumber 
    FROM products
) t
WHERE (t.RowNumber - 1) % 5 = 0 

Demo here

答案 1 :(得分:3)

您可以从年份中减去模5并以此为基。

SELECT (year-(year%5))||'-'||(year-(year%5)+4) AS years
FROM products 
GROUP BY year-(year%5)

从数中减去最接近的较低N数时,模数N是余数。
例如:

11%5 = 11 - 10 = 1 
8%5 = 8 - 5 = 3

因此,通过从年份中减去它,可以得到最接近的5位数

2018 - 2018%5 = 2018 - 3 = 2015

舍入年份的另一种方法是将其除以5

SELECT (CAST(year/5 AS INTEGER)*5)||'-'||MAX(year) AS years
FROM products 
GROUP BY CAST(year/5 AS INTEGER)*5;

db <>小提琴here

的测试

答案 2 :(得分:2)

SQL数据库结构和数据

CREATE TABLE tablename
(
    `year` INTEGER
);

INSERT INTO tablename
VALUES      (2000),
            (2001),
            (2002),
            (2003),
            (2004),
            (2005),
            (2006),
            (2007),
            (2008),
            (2009),
            (2010),
            (2011),
            (2012),
            (2013),
            (2014);  

SQL查询

SELECT ( Min(year) || '-' || Max(year) ) AS Col1
FROM   (SELECT year,
               Row_number() OVER (partition BY year % 5 ORDER BY year) AS RowNumber
        FROM   tablename) tmp
GROUP  BY rownumber

结果

+-----------+
|   Col1    |
+-----------+
| 2000-2004 |
| 2005-2009 |
| 2010-2014 |
+-----------+

在线演示:https://www.db-fiddle.com/f/5rHUda17KRtsA3ZAzoLDrE/0


参考
1. SQLite-运算符:https://www.tutorialspoint.com/sqlite/sqlite_operators.htm