2013-07-26 72 views
0

這裏是我的表即book_master有以下詳細怎樣用DATEDIFF函數兩個日期之間diffrence動態使用SQL Server 2008

id  book_nmae  book_cost publish_date 
6 maths   150.0000  1992-08-06 
7 science  120.0000  1992-08-07 
8 gujrati  100.0000  1992-08-08 
9 english  105.0000  1992-08-09 
10 social study 100.0000  1992-08-10 

在這裏,我想出版日期1992年8月6日和1992之間diffrence 08-07使用book_name列。

我曾嘗試以下條件爲sql

SELECT DATEDIFF(DAY,book_master.publish_date,book_master.publish_date) 
from book_master where book_name in('science','maths') 

select DATEDIFF(DAY,book_master.publish_date.book_name('maths'),book_master.publish_date.book_name('science')) 
from book_master 

問候 rajdeep帕爾馬

回答

1
DECLARE @Date1 AS DATETIME 
DECLARE @Date2 AS DATETIME 

SELECT @Date1 = publish_date 
FROM book_master 
WHERE book_name = 'science' 

SELECT @Date2 = publish_date 
FROM book_master 
WHERE book_name = 'maths' 

SELECT DATEDIFF(DAY,@Date1,@Date2) 
+0

上'(BOOK_NAME)的唯一索引'會有所幫助。 –

0

另一個解決方案是

SELECT DATEDIFF(DAY,T1.publish_date,T2.publish_date) 
FROM 
    (
    SELECT publish_date 
    FROM book_master 
    WHERE book_name = 'science' 
) T1 
CROSS JOIN 
    (
    SELECT publish_date 
    FROM book_master 
    WHERE book_name = 'maths' 
) T2 
0

不是按名稱搜索書,我會使用的id假設那些id是獨一無二的。 解決方案:

DECLARE @MyTable TABLE(
    id INT PRIMARY KEY, -- this PK constraint ensures unique values for this column 
    book_name NVARCHAR(200) NOT NULL, 
    publish_date DATE NOT NULL 
); 

INSERT @MyTable(id,book_name,publish_date) 
VALUES 
(6 ,'maths  ', '1992-08-06'), 
(7 ,'science  ', '1992-08-07'), 
(8 ,'gujrati  ', '1992-08-08'), 
(9 ,'english  ', '1992-08-09'), 
(10,'social study', '1992-08-10'); 

DECLARE @book_id_1 INT, 
     @book_id_2 INT; 
SELECT @book_id_1=6, 
     @book_id_2=7;  

SELECT DATEDIFF(DAY,pvt.[1],pvt.[2]) AS DaysDiff 
FROM(  
    SELECT t.publish_date, 
      ROW_NUMBER() OVER(ORDER BY t.publish_date) AS RowNum 
    FROM @MyTable t 
    WHERE t.id IN (@book_id_1,@book_id_2) 
) x 
PIVOT(MAX(x.publish_date) FOR x.RowNum IN ([1],[2])) pvt; 

結果:

DaysDiff 
----------- 
1 
相關問題