在where子句之间使用select查询

时间:2013-04-17 21:34:24

标签: sql sql-server tsql

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

答案 0 :(得分: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;

答案 1 :(得分: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

答案 2 :(得分: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)

答案 3 :(得分: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!

相关链接: