SQL问题在两个日期之间查询数据库

时间:2014-11-08 05:44:04

标签: sql sql-server sql-server-2008

我在下面的数据库中有以下记录是每条记录的创建日期。

2013-11-09 12:55:43.000
2013-10-29 19:01:53.000
2013-10-29 04:59:42.000

我的SQL查询看起来像这样

Select d.Name as DealerName, Sum(c.CommissionAmount) as CommissionAmount
from Dealer d
Left join Commission c on c.Dealerid = d.DealerId
where c.CreatedDate between isnull(@FromDate, c.CreatedDate) and isnull(@ToDate, c.CreatedDate)
Group by d.Name
Order by CommissionAmount desc

当我在搜索功能中输入以下日期时

从日期= 29/10/2013
迄今为止= 09/11/2013

它只返回一条记录,当它应该返回三条时,但是如果我离开日期原样并传入null为了日期我得到两条记录

有人能告诉我这里我做错了什么吗?

由于

4 个答案:

答案 0 :(得分:0)

试试这个:

Dates子句中使用where时,请始终在两侧使用相同的投射

Select d.Name as DealerName, Sum(c.CommissionAmount) as CommissionAmount
from Dealer d
Left join Commission c on c.Dealerid = d.DealerId
where CAST(c.CreatedDate as DATE) between 
CAST(isnull(@FromDate, c.CreatedDate) as DATE) and 
CAST(isnull(@ToDate, c.CreatedDate) as DATE)
Group by d.Name
Order by CommissionAmount desc

答案 1 :(得分:0)

问题是你已经定义了没有时间的变量所以@todate就像'2013-11-09 00:00:00.000'

但是在表格日期有时间。运算符之间不会考虑这个日期'2013-11-09 12:55:43.000',因为它高于你提到的那些日期,你得到两行。

所以试试这个。

CREATE TABLE #temp
  (dates DATETIME)

INSERT INTO #temp
VALUES     ('2013-11-09 12:55:43.000'),
            ('2013-10-29 19:01:53.000'),
            ('2013-10-29 04:59:42.000')


DECLARE @from VARCHAR(50)='29/10/2013',
        @to   VARCHAR(50) ='09/11/2013'

SELECT *
FROM   #temp
WHERE  (@from is not null and @to is not null and Cast(dates AS DATE) BETWEEN CONVERT(DATE, @from, 103) AND CONVERT(DATE, @to, 103) ) or 1=1

<强> SQL FIDDLE DEMO

答案 2 :(得分:0)

你可以用一种方式来做到这一点

<强> 1。 CAST

 CAST(c.CreatedDate as DATE)

<强> 2。 CONVERT

CONVERT(varchar(10), c.CreatedDate)

以下是您可以实现的两种方式。

1.  where 
    CONVERT(varchar(10), c.CreatedDate)
    between 
    isnull(@FromDate, c.CreatedDate) 
    and 
    isnull(@ToDate, c.CreatedDate)


 2. where 
    CAST(c.CreatedDate as DATE)
    between 
    isnull(@FromDate, c.CreatedDate) 
    and 
    isnull(@ToDate, c.CreatedDate)

演员与演出之间的差异convert是你可以在CONVERT函数中应用你需要的任何样式格式。CONVErT函数有Refer这个链接有很多日期时间格式你将获得SQL中的所有样式格式

COnvert的语法是

CONVERT ( data_type [ ( length ) ] , expression [ , style ] )

其中expression [ , style ]是可选字段。

CAST

在SQL 2005版本之后可以使用Cast.cast还在SQL Server中将一种数据类型的表达式转换为另一种数据类型。 的语法

CAST ( expression AS data_type [ ( length ) ] )

[ ( length ) ]是Cast

中的可选字段

答案 3 :(得分:0)

试试这个

    SELECT      d.Name as DealerName, Sum(c.CommissionAmount) as CommissionAmount
    FROM        Dealer d
    LEFT JOIN   Commission c on c.Dealerid = d.DealerId
    WHERE       CONVERT(VARCHAR(10),CAST(c.CreatedDate AS DATE),103) 
                BETWEEN isnull(@FromDate, c.CreatedDate) and isnull(@ToDate, c.CreatedDate)
    Group by    d.Name
    Order by    CommissionAmount desc