日期减去日期查询

时间:2014-09-27 01:58:33

标签: sql sql-server date

我有一个如下所示的查询,我想对end_scan-packing_date列进行计算,我该如何实现?

 SELECT a.invoice_no,
       CONVERT(VARCHAR, b.packing_date,3) as packing_date ,
       CONVERT(VARCHAR, b.exw_date,3) as exw,
       CONVERT(VARCHAR, b.bcd_end_date, 3) as end_date,
       (SELECT TOP 1 insert_date FROM   wms.bcd_shipment d,wms.shinvoicedetails WHERE d.invoice_no = a.invoice_no ORDER  BY insert_date ASC) as start_date ,
       (SELECT TOP 1 insert_date FROM   wms.bcd_shipment d,wms.shinvoicedetails WHERE d.invoice_no = a.invoice_no ORDER  BY insert_date DESC) as end_scan,
       CONVERT(VARCHAR, send_date, 3) as swnd_date,customer_short_name,
       Sum(picking_qty) as qty,total_carton
FROM   wms.shinvoicedetails a,
       wms.shinvoiceheder b,
       wms.shinvoice_ctrl c
WHERE  send_date BETWEEN '2014/8/26 00:00:01' AND '2014/9/25 23:59:59'
       AND a.invoice_no = b.invoice_no
       AND a.invoice_no = c.invoice_no
GROUP  BY a.invoice_no,
          b.packing_date,
          b.exw_date,
          b.bcd_end_date,
          send_date,
          customer_short_name,
          total_carton
ORDER  BY 1;  

2 个答案:

答案 0 :(得分:1)

我可以向您推荐DATEDIFF函数的文档(我假设您将SQL Server用作RDBMS)。

它有3个参数,我假设你想要天数的差异。所以你想要的东西会是这样的:

DATEDIFF(DAY,
         (SELECT TOP 1 insert_date
          FROM   wms.bcd_shipment d,
                 wms.shinvoicedetails
          WHERE  d.invoice_no = a.invoice_no
          ORDER  BY insert_date DESC),
          b.packing_date
) AS diff_days

但您的查询在许多级别上都是错误的。您正在对几乎所有列进行分组以获取SUM,而您应将其编写为a derived table(子查询)仅在必要字段上进行分组。您也转换为VARCHAR,可能转换为VARCHAR(1)。您应该将其写为CONVERT(VARCHAR(10),< your date field>,3)。

答案 1 :(得分:1)

一天不在00:00:01开始,并且没有以23:59:59结束。帮助自己不要试图将您的需求扩展到between的语法。有一种更简单,更可靠的方法

WHERE  send_date >= '20140826' AND send_date < '20140926'

少于26日;它更准确&amp;没有愚蠢的一秒扣除。

  

日期和时间范围的最佳做法是避免BETWEEN和   总是使用表格:

     

WHERE col&gt; =&#39; 20120101&#39; AND col&lt; &#39; 20120201&#39;

     

此表单适用于所有人   类型和所有精度,无论时间部分是什么   适用。

     

Itzik Ben-Gan

http://sqlmag.com/t-sql/t-sql-best-practices-part-2