SQL Server之间的语句

时间:2018-02-13 16:51:50

标签: sql sql-server between

我有两列,年份和工资期(1,2,3,4 ......)。我正绞尽脑汁试图弄清楚如何根据这些来做一个介于两者之间。

例如说我有:

2017      1
2017      2
2017      3
2017      4
-------------v   
2017      5
2017      6
...
2017      51
2017      52 (typically, not guaranteed to be 52 periods)
2018      1
2018      2
2018      3
2018      4
-------------^
2018      5
...

我希望选择2017(5)和2018(4)之间的所有行,我该怎么做?我尝试了几种不同的方法,但无法弄明白。薪酬期通常是1-52,但我不能指望。

3 个答案:

答案 0 :(得分:6)

一个选项

Select * 
 from YourTable
 Where ([Year]*100)+[PayPeriod] between 201705 and 201804

答案 1 :(得分:0)

一般来说,你可以用两个条件来处理这个问题。

declare @yr int = 2018, @period = 5;

select * from t
where
       yr = @yr     and period <= @period
    or yr = @yr - 1 and period >= @period

我不知道你将如何通过截止期,但有许多方法可能是合适的:

-- period number is supplied as an argument
with lp(last_period) as (
    select 4
)
select yr, period
from T cross join lp
where
        yr = year(current_timestamp)     and period <= last_period 
    or  yr = year(current_timestamp) - 1 and period >= last_period;


-- assumes the "last" row in the table is the cutoff
with lp(last_period) as (
    select distinct first_value(period) over (order by yr desc, period desc)
    from T 
)
select yr, period
from T cross join lp
where
        yr >= year(current_timestamp) - 1
    and yr  = year(current_timestamp) or period >= last_period;


-- calculates period based on current date??
with lp(last_period) as (
    select datepart(week, current_timestamp)
)
select yr, period
from T cross join lp
where
        yr = year(current_timestamp)     and period <= last_period 
    or  yr = year(current_timestamp) - 1 and period >= last_period;

答案 2 :(得分:0)

如果行数较少,我会回答@JohnCappelletti的回答。它简单易懂。

如果您有大量行,并且需要优化查询以使用索引,那么您希望避免计算您正在搜索的字段(并避免OR条件)< / em>的。因此我会使用像...这样的东西。

SELECT * FROM yourTable WHERE yr = 2016 AND period >= 5
UNION ALL
SELECT * FROM yourTable WHERE yr = 2017 AND period <  5

但实际上,我建议更改表格的结构。正如你已经发现,当你将比例分成两个字段时,过滤范围是“尴尬的”。

一种选择可能是使用代表每个支付期开始的DATE字段。

或者可能在每个报告期间都有一个单独的表格......

CREATE TABLE dim_pay_period (
  id               INT IDENTITY(1,1),
  start_date       DATE,
  year             INT,
  period           INT,          -- The 1-52(ish) that you're using
  year_period      INT,          -- 201705, for example
  num_working_days INT           -- Just an example...
)

然后您的数据表将有一个列“pay_year_period”,如果您需要查找有关该year_period的信息,您可以加入维度表。