0

我必须找出一个日期介于其他两个日期之间,这些日期是从 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

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

谢谢

尚卡尔。

4

4 回答 4

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;
于 2013-04-17T21:38:45.773 回答
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
于 2013-04-17T21:38:16.120 回答
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)
于 2013-04-17T21:39:06.213 回答
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!

相关链接:

于 2013-04-17T21:43:58.930 回答