如何在2个不同年份和2个不同季度之间选择年份和季度?

时间:2019-04-18 06:36:12

标签: sql sql-server tsql

我有这张桌子:

year    | quarter
2018    | 1
2018    | 2
2018    | 3
2018    | 4
2019    | 1
2019    | 2
2019    | 3
2019    | 4

我需要从该表中选择2018年第二季度和2019年第三季度之间的所有数据

我发现只选择开始日期:

SELECT  *
FROM    [usa].[dbo].[tmpDate]
WHERE   year != 2018
OR      quarter >= 2

返回我的

year    | quarter
2018    | 2
2018    | 3
2018    | 4
2019    | 1
2019    | 2
2019    | 3
2019    | 4

应该选择什么来获得:

year    | quarter
2018    | 2
2018    | 3
2018    | 4
2019    | 1
2019    | 2
2019    | 3

3 个答案:

答案 0 :(得分:2)

您可以使用以下查询来获得预期的结果:

SELECT * 
FROM [usa].[dbo].[tmpDate] 
WHERE (year = 2018 AND quarter >= 2) OR
      (year = 2019 AND quarter <= 3);

包含示例数据的演示

DECLARE @TempData TABLE ([year] INT, [quarter] INT);

INSERT INTO @TempData ([year], [quarter]) VALUES
(2018, 1),
(2018, 2),
(2018, 3),
(2018, 4),
(2019, 1),
(2019, 2),
(2019, 3),
(2019, 4);

SELECT * 
FROM @TempData
WHERE ([year] = 2018 AND [quarter] >= 2) OR
      ([year] = 2019 AND [quarter] <= 3);

输出:

year    quarter
---------------
2018    2
2018    3
2018    4
2019    1
2019    2
2019    3

答案 1 :(得分:1)

一种可能的方法是使用yearquarter值进行小的计算:

-- Table
CREATE TABLE #Data (
   [year] int,
   [quarter] int
)
INSERT INTO #Data
   ([year], [quarter])
VALUES   
   (2018, 1),
   (2018, 2),
   (2018, 3), 
   (2018, 4), 
   (2019, 1), 
   (2019, 2), 
   (2019, 3), 
   (2019, 4)

-- Statement
SELECT *
FROM #Data
WHERE ([year] * 10 + [quarter]) BETWEEN 20182 AND 20193
ORDER BY [year], [quarter]

输出:

----------------
year    quarter
----------------
2018    2
2018    3
2018    4
2019    1
2019    2
2019    3

答案 2 :(得分:0)

在WHERE子句中,括号起着重要作用。尝试以下操作,让我知道它是否有效:

SELECT * 
FROM YourTable 
WHERE (year = 2018 AND quarter >= 2) 
      OR (year = 2019 AND quarter <= 3)