无法解释两个查询之间的差异

时间:2015-10-02 15:45:44

标签: sql sql-server-2012

我有以下查询:

SELECT DISTINCT 
    MONTH(T0.DocDate) AS 'Months', 
    SUM(isnull(T1.InvQty,0)) - SUM(isnull(T2.InvQty,0)) AS 'Normal Scrap Tons', 
    SUM(round(T1.LineTotal * (100 - isnull(T0.DiscPrcnt,0)) / 100,2)) - SUM(isnull(T2.LineTotal,0)) AS 'Normal Scrap Purchase Value'
FROM 
    OPCH T0 
INNER JOIN 
    PCH1 T1 ON T0.[DocEntry] = T1.[DocEntry] 
LEFT OUTER JOIN
    RPC1 T2 ON T0.DocNum = T2.BaseRef 
LEFT OUTER JOIN 
    ORPC T3 ON T2.DocEntry = T3.DocEntry 
WHERE 
    T1.ItemCode IN ('Scrap-02') 
    AND YEAR(T0.DocDate) = YEAR('2015-09-15')
GROUP BY 
    MONTH(T0.DocDate)

返回:

enter image description here

但是当我运行以下查询时,指定第9个月(9月),

SELECT DISTINCT 
    MONTH(T0.DocDate) AS 'Months', 
    SUM(isnull(T1.InvQty,0)) - SUM(isnull(T2.InvQty,0)) AS 'Normal Scrap Tons', 
    SUM(round(T1.LineTotal * (100 - isnull(T0.DiscPrcnt,0)) / 100,2)) - SUM(isnull(T2.LineTotal,0)) AS 'Normal Scrap Purchase Value'
FROM 
    OPCH T0  
INNER JOIN 
    PCH1 T1 ON T0.[DocEntry] = T1.[DocEntry] 
LEFT OUTER JOIN
    RPC1 T2 ON T0.DocNum = T2.BaseRef 
LEFT OUTER JOIN 
    ORPC T3 ON T2.DocEntry = T3.DocEntry 
WHERE 
    T1.ItemCode IN ('Scrap-02') 
    AND T0.DocDate BETWEEN '2015-09-01' AND '2015-09-15'
GROUP BY 
    MONTH(T0.DocDate)

我得到以下结果:

enter image description here

检查所有其他已完成的月份,即添加:T0.DocDate BETWEEN' 2015-08-01' AND' 2015-08-31',结果与8月份的上述热门查询没有任何差异。

为什么我在9月中旬不完整的月份(数据库I,m使用在9月中旬备份)中得到了差异

2 个答案:

答案 0 :(得分:2)

假设docDate没有时间成分,那么请尝试放入9月的最后一天:

WHERE T1.ItemCode IN ('Scrap-02') AND
      T0.DocDate BETWEEN '2015-09-01' AND '2015-09-30'

如果您不想担心时间组件,请使用:

WHERE T1.ItemCode IN ('Scrap-02') AND
      T0.DocDate >= '2015-09-01' AND T0.DocDate < '2015-10-01'

答案 1 :(得分:2)

我会在你的问题上指出这一部分

  

为什么我会在9月中旬的不完整月份得到改变(数据库I&#39; m使用在9月中旬备份)

如果你只有九月的一半,那么两个查询应该是相等的。所以我猜你在2015-09-15

之后有一些数据

所以要进行验证验证

SELECT *
FROM OPCH T0
WHERE T0.DocDate > `2015-09-15`