我必须找出一个日期介于两个其他日期之间,这两个日期是从Microsoft SQL Server的另一个表中选择的

即我想做类似的事情

     Select A.* from  ( select member.key, 
           case when effective_date between (select month_start and month_end 
           from sales_month 
           where month=2 and year=2013) bucket_1
           then 1 else 0 from member ) as A
          where a.bucket_1 != 0

我必须重复不同月份的案例陈述。 有什么想法/帮助吗?

谢谢

香卡

===============>>#1 票数:5

这可以通过JOIN完成:

SELECT m.* 
FROM member m
JOIN sales_month sm
    ON sm.month = 2
    AND sm.year = 2013
    AND m.effective_date BETWEEN sm.month_start AND sm.month_end;

===============>>#2 票数:4 已采纳

使用变量保存信息。

DECLARE @StartDate DATETIME,
        @EndDate DATETIME
SELECT @StartDate = month_start
       , @EndDate = month_end
FROM sales_month
WHERE [month] = 2 AND [year] = 2013

SELECT *
from member
where effective_date BETWEEN @StartDate AND @EndDate

===============>>#3 票数:1

如果没有期望的重复项,则可以使用联接:

select m.*
from member m join
     sales_month sm
     on m.effective_date between sm.month_start and sm.month_end and
        sm.month = 2 and sm.year = 2013

否则,请尝试使用一个exists的相关子查询:

select m.*
from member m
where exists (select 1 from sales_month where month=2 and year=2013 and m.effective_date between month_start and month_end)

===============>>#4 票数:0

不知道为什么需要从表中获取月份和年份。 您正在寻找所有生效日期为2013年2月的会员,对吗? sales_month在这里为您做什么?

DECLARE @m INT, @y INT;
SELECT @m = 2, @y = 2013;


DECLARE @d DATETIME;
SET @d = DATEADD(MONTH, @m-1, DATEADD(YEAR, @y-1900, 0));

SELECT m.*            -- don't use SELECT *!
 FROM dbo.member AS m -- always use schema prefix!
  WHERE effective_date >= @d 
  AND effective_date < DATEADD(MONTH, 1, @d); -- don't use BETWEEN!

如果它需要来自表(例如,由于某种原因您的销售月份与日历月份不同),则可以使用联接,但是我不确定您的BETWEEN逻辑到底意味着什么。 如果逻辑上合理,我会保留它,但是在大多数情况下,它不是。

SELECT m.*
 FROM dbo.member AS m
 INNER JOIN dbo.sales_month AS s
 ON m.effective_date BETWEEN s.month_start AND s.month_end
 WHERE s.[month] = 2 AND s.[year] = 2013; -- don't use reserved words as column names!

相关链接:

  ask by Shankar translate from so

未解决问题?本站智能推荐: