0

这是我的表,即 book_master,具有以下详细信息

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

在这里,我想使用 book_name 列获取 publish_date 1992-08-06 和 1992-08-07 之间的差异。

我已经尝试了以下条件到 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 parmar

4

3 回答 3

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)
于 2013-07-26T12:41:04.397 回答
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
于 2013-07-26T12:43:39.517 回答
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
于 2013-07-26T13:12:45.887 回答