SQL - 带子查询的DATEDIFF

时间:2015-05-28 12:07:22

标签: sql sql-server datediff

我需要从server { listen 80; listen [::]:80 default_server ipv6only=on; server_name premium.bookboon.com; return 301 https://$server_name$request_uri; } server { listen 443 ssl; root /var/www/premium/web; server_name premium.bookboon.com; ssl_certificate /etc/ssl/certs/premium.bookboon.com_bundle.crt; ssl_certificate_key /etc/ssl/private/premium.bookboon.com.key; location / { # try to serve file directly, fallback to rewrite try_files $uri @rewriteapp; } location @rewriteapp { # rewrite all to app.php rewrite ^(.*)$ /app.php/$1 last; } location ~ ^/(app|config|test)\.php(/|$) { fastcgi_pass 127.0.0.1:9000; fastcgi_split_path_info ^(.+\.php)(/.*)$; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param HTTPS off; fastcgi_param ENVIRONMENT "prod"; } error_log /var/log/nginx/premium_error.log; access_log /var/log/nginx/premium_access.log; } DB下游传递一个值,这实际上是两个SQL Server之间的差异。使用timestamps函数这很简单。

DATEDIFF

但是,在传递值时,代码只知道订单ID值而不是上面显示的2个时间戳。因此,我需要SELECT DATEDIFF(day, '2015-11-06 00:00:00.000','2015-12-25 00:00:00.000') AS DiffDate ; 信息来自子查询,或者我认为的其他内容。子查询的主要细节如下:

timestamp

我尝试了几种不同的方式,但没有一种方法是成功的。最新的我已经厌倦了,从语法角度看起来还不错,但我收到了错误:

  

从字符转换日期和/或时间时转换失败   串

我永远不会确定如何应对或处理。

select O.DATE1 , C.DATE2
from TABLE1 O, TABLE2 C
WHERE O.VALUE1_ID = C.VALUE1
AND O.order_id = '12345678' 

任何指示或帮助都将不胜感激。

4 个答案:

答案 0 :(得分:2)

子查询不应该是字符串,因此请删除单引号。另外,你谈论O.DATE1和C.DATE2,所以你可能意味着这样的事情:

select DATEDIFF (day, 
              (select O.DATE1 
                 from TABLE1 O 
                where O.VALUE1 = 16650476) , 
              (SELECT C.DATE2 
                from TABLE1 O, TABLE2 C 
                WHERE O.VALUE1 = C.VALUE2 AND O.order_id = 12345678)) AS DIFFDATE; 

答案 1 :(得分:0)

我想你想要以下内容:

[{a:0, b:1, c:3}, {a:3, b:2, c:4}]

答案 2 :(得分:0)

你可以声明两个变量datetime然后对这两个变量进行约会吗?

DECLARE @FirstDate AS datetime
DECLARE @SecondDate AS datetime
SET @FirstDate = (select O.VALUE1 from TABLE1 O where O.VALUE1 = 16650476)
SET @SecondDate = (SELECT C.VALUE1 from TABLE1 O, TABLE2 C WHERE O.VALUE1 = C.VALUE2 AND O.order_id = 12345678)
SELECT DATEDIFF(day, @FirstDate, @SecondDate)

答案 3 :(得分:0)

你能尝试以下我使用你的子查询但是有关表“Table1”和“Table2”中数据的更多信息会很有用

SELECT
    DATEDIFF(day, D.Date1, D.Date2) AS DiffDate 
FROM
(
    select O.DATE1 as Date1 , C.DATE2 as Date2
    from TABLE1 O, TABLE2 C
    WHERE O.VALUE1_ID = C.VALUE1
    AND O.order_id = '12345678' 
) D

您收到错误的原因

  

从字符转换日期和/或时间时转换失败   串

是因为您将字符串(下方)传递给datediff函数而不是使用日期

'(select O.VALUE1 
from TABLE1 O 
where O.VALUE1 = 16650476)'