2016-09-07 59 views
-3

我選擇回到2時18分07秒SQL Server 2012中得到的結果作爲JSON

;WITH DEMO(ID, FromTime, ToTime) AS 
(
    SELECT TOP 1 
     ID 
     ,CONVERT(DATETIME,FromTime,120) AS FromTime 
     ,CONVERT(DATETIME,ToTime,120) AS ToTime 
    FROM (VALUES (1,'2016-09-03 18:14:47.000','2016-09-03 20:32:54.000') 
       ,(2,'2016-09-03 12:35:45.000','2016-09-03 15:06:06.000') 
    ) AS X(ID,FromTime,ToTime) 
) 
SELECT 
    DATEADD(SECOND,SUM(DATEDIFF(SECOND, k.FromTime, k.ToTime)) OVER 
     (
      PARTITION BY (SELECT NULL) 
     ),CONVERT(TIME(0),'00:00:00',0)) AS TIME_SUM 
FROM DEMO k; 

我怎樣才能得到結果如下?

「{\」 returnDate \ 「:[{\ 」TIME_SUM \「:\ 」02:18:07 \「}]}」

+0

你是否使用了JSON SQL Server 2016呢?您的查詢中甚至沒有任何內容甚至會將其作爲JSON返回。 – dfundako

+0

哪個sql server版本? – techspider

+0

JSON僅在2016年。 – dfundako

回答

0

沒有足夠的細節,你正在努力實現;如果你真的希望只輸出問題中顯示的一個值,那麼一個醜陋的解決方案就是這樣的:

;WITH DEMO(ID, FromTime, ToTime) AS 
(
    SELECT TOP 1 
     ID 
     ,CONVERT(DATETIME,FromTime,120) AS FromTime 
     ,CONVERT(DATETIME,ToTime,120) AS ToTime 
    FROM (VALUES (1,'2016-09-03 18:14:47.000','2016-09-03 20:32:54.000') 
       ,(2,'2016-09-03 12:35:45.000','2016-09-03 15:06:06.000') 
    ) AS X(ID,FromTime,ToTime) 
) 
SELECT 
    '{\"returnDate\" : [ {\"TIME_SUM\":\"' + 
    CONVERT(VARCHAR(20),DATEADD(SECOND,SUM(DATEDIFF(SECOND, k.FromTime, k.ToTime)) OVER 
    (
      PARTITION BY (SELECT NULL) 
    ),CONVERT(TIME(0),'00:00:00',0))) + '\"}]}' AS TIME_SUM 
FROM DEMO k