选择两个日期之间的查询

时间:2013-01-17 11:35:52

标签: sql sql-server tsql visual-studio-2008

我正在尝试在数据库中的两个特定日期之间进行选择连接

我认为这是正确的道路,但不正确

我怎样才能让它发挥作用

SELECT --RTRIM(C.CustomerFirstName) + ' ' + LTRIM(C.CustomerLastName) as CustomerFullName,
       ROW_NUMBER() OVER(ORDER BY CP.ActionDate) AS RowNumber,
       C.CustomerFirstName,
       C.CustomerLastName,
       C.CustomerCompany,
       C.CustomerPosition,
       C.CustomerCountry,
       C.CustomerProvince,
       C.CustomerContact,
       CP.ActionDate,
       CP.ProductCode,
       CP.CustomerEmail
FROM   tblCustomers C
       JOIN tblCustomerProducts CP
            ON  C.CustomerEmail = CP.CustomerEmail


     ORDER BY ActionDate DESC
WHERE CP.ActionDate BETWEEN '1/17/2013' AND '19/12/2012'

4 个答案:

答案 0 :(得分:7)

而不是

WHERE CP.ActionDate BETWEEN '1/17/2013' AND '19/12/2012`

试试这个:

WHERE CP.ActionDate BETWEEN '19/12/2012' AND '1/17/2013'

请注意:这是因为SQL Server中的BETWEEN谓词非对称,这意味着value1 BETWEEN value2 AND value3与{Value1 >= Value2 AND Value1 <= Value3相同1}},因此value2之前的值AND必须小于或等于value3

答案 1 :(得分:4)

必须首先列出较小的日期

BETWEEN '12/19/2012'  AND '1/17/2013'

答案 2 :(得分:3)

您当前的查询存在一些问题。

首先,您的日期顺序错误。

其次,您将ORDER BY放在错误的位置。 ORDER BY是您选择中列出的最后一项:

FROM tblCustomers C
JOIN tblCustomerProducts CP 
   ON C.CustomerEmail = CP.CustomerEmail
WHERE CP.ActionDate BETWEEN  '12/19/2012' AND '1/17/2013'
ORDER BY ActionDate DESC

您也可以使用:

FROM tblCustomers C
JOIN tblCustomerProducts CP 
   ON C.CustomerEmail = CP.CustomerEmail
WHERE CP.ActionDate >= '12/19/2012' AND CP.ActionDate <= '1/17/2013'
ORDER BY ActionDate DESC

我还建议您确保以相同的方式格式化日期。您有一个DD/MM/YYYY,另一个为MM/DD/YYYY

答案 3 :(得分:2)

你错放了日期,它应该在第一个位置较小而在第二个位置较大:

WHERE CP.ActionDate BETWEEN '19/12/2012' AND '1/17/2013'

OR

WHERE CP.ActionDate >= '19/12/2012' AND CP.ActionDate <= '1/17/2013'