根据日期时间加入两个表格
CREATE Table A
(StartDate DATETIME,
EndDate DATETIME,
Name VARCHAR(50))
CREATE Table B
(FromDate DATETIME,
ToDate DATETIME,
Product VARCHAR(50),
Price VARCHAR(50))
INSERT INTO A values ('05/20/2014 10:00:00', '05/20/2014 14:00:00', 'Stalin')
INSERT INTO A values ('05/20/2014 14:02:00', '05/20/2014 18:03:00', 'Vipin')
INSERT INTO A values ('05/20/2014 18:10:00', '05/20/2014 23:04:00', 'Raju')
INSERT INTO B values ('05/20/2014 10:01:00', '05/20/2014 14:01:00', 'Pen', '20')
INSERT INTO B values ('05/20/2014 14:02:33', '05/20/2014 18:03:58', 'Pensil', '22')
INSERT INTO B values ('05/20/2014 18:11:00', '05/20/2014 23:05:00', 'Book','33')
结果应为
StartDate EndDate FromDate ToDate Product Price Name
5/20/2014 10:00 | 5/20/2014 14:00 | 5/20/2014 10:01 | 5/20/2014 14:01 | Pen | 20 | Stalin
5/20/2014 14:02 | 5/20/2014 18:03 | 5/20/2014 14:02 | 5/20/2014 18:03 | Pensil | 22 | Vipin
5/20/2014 18:10 | 5/20/2014 23:04 | 5/20/2014 18:11 | 5/20/2014 23:05 | Book | 33 | Raju
我正在尝试以下查询
Select A.StartDate,a.EndDate, b.FromDate, b.ToDate, b.Product,b.Price,a.Name
from a
Join B
ON A.StartDate BETWEEN DATEADD(MM,-2,B.FromDate)
AND DATEADD(MM,2,B.ToDate)
结果不符合预期,有什么帮助吗?
答案 0 :(得分:0)
所有日期都在2个月之内。我假设你真的想要分钟。试试这个:
Select A.StartDate,a.EndDate, b.FromDate, b.ToDate, b.Product, b.Price,a.Name
from a Join
B
ON A.StartDate BETWEEN DATEADD(minute,-2,B.FromDate) AND DATEADD(minute,2,B.ToDate);
Here是有效日期部分的列表。
使用dateadd()
和datepart()
等功能时,请使用本机的全名。没有理由使用缩写。即使您认为自己知道MM
的含义,也可能不会有其他人阅读您的代码。
答案 1 :(得分:0)
希望这就是你要找的东西
SELECT A.StartDate,
A.EndDate,
B.FromDate,
B.ToDate,
B.Product,
B.Price,
A.Name
FROM A
JOIN B ON DATEPART(HH,A.StartDate) = DATEPART(HH,B.FromDate)
AND CAST(A.StartDate AS DATE) = CAST(B.FromDate AS DATE)
获得结果