这是我的问题的新版本,因为它似乎令人困惑。对不起。我想到了。有兴趣可以看代码。要解决的笔记在那里。谢谢你的帮助!
我让它工作这么远,但OriginaionL(L代表Little,B代表Big)不正确。它采用正确的日期,但不是起源。
CREATE TABLE MyTable
(
LoadTagID INT,
EnteredDateTime datetime,
JobNumber VARCHAR(50),
Origination VARCHAR(50)
)
INSERT INTO MyTable VALUES
(1, '2015-02-09 00:00:00.00', 11111, 'Here')
,(2, '2015-02-09 00:00:00.00', 22222, 'There')
,(3, '2016-03-09 00:00:00.00', 11111, 'Outside')
,(4, '2016-08-09 00:00:00.00', 12578, 'Anywhere')
,(252, '2017-06-29 00:00:00.00', 12345, 'Here')
,(253, '2017-08-01 00:00:00.00', 99999, 'There')
,(254, '2017-08-04 00:00:00.00', 12345, 'Outside')
,(255, '2017-08-09 00:00:00.00', 12345, 'Anywhere')
,(256, '2017-08-10 00:00:00.00', 99999, 'Anywhere')
,(257, '2017-08-10 00:00:00.00', 123456, 'Anywhere')
,(258, '2017-08-11 00:00:00.00', 123456, 'Over Yonder')
,(259, '2017-08-13 00:00:00.00', 99999, 'Under The Bridge')
--Select * From MyTable
CREATE TABLE #LTTB1 --MAX
(
LoadTagID varchar(50),
JobNumber varchar(50),
EnteredDateTime varchar(50),
Origination varchar(50)
)
CREATE TABLE #LTTB2 --MIN
(
LoadTagID varchar(50),
JobNumber varchar(50),
EnteredDateTime varchar(50),
Origination varchar(50)
)
CREATE TABLE #LTTB3
(
LoadTagIDL varchar(50),
JobNumberL varchar(50),
EnteredDateTimeL
varchar(50),
OriginationL varchar(50)
, LoadTagID varchar(50),
JobNumber varchar(50),
EnteredDateTime varchar(50),
Origination varchar(50)
)
INSERT INTO #LTTB1
SELECT
MAX(LoadTagID) AS LoadTagID,
JobNumber,
MAX(EnteredDateTime) AS EnteredDateTime,
MAX(Origination) AS Origination
FROM MyTable
WHERE CONVERT (Date, EnteredDateTime) >= CONVERT (Date, GETDATE()-10) --Gets the last 10 days.
GROUP BY JobNumber ORDER BY JobNumber
INSERT INTO #LTTB2
SELECT MIN(LoadTagID) AS LoadTagIDL,
JobNumber AS JobNumberL,
MIN(EnteredDateTime) AS EnteredDateTimeL,
MAX(Origination) AS OriginationL --MAX! This needed to be max!! Why?
FROM MyTable
Where CONVERT (Date, EnteredDateTime) >= CONVERT (Date, GETDATE()-60) --Goes further back in case one is a long.
GROUP BY JobNumber ORDER BY JobNumber
INSERT INTO #LTTB3
SELECT L.LoadTagID AS LoadTagIDL
, L.JobNumber AS JobNumberL
, L.EnteredDateTime AS EnteredDateTimeL
, L.Origination AS OriginationL
, B.LoadTagID, B.JobNumber, B.EnteredDateTime, B.Origination
FROM #LTTB1 B --MAX
INNER JOIN #LTTB2 L ON B.JobNumber = L.JobNumber
Select * From #LTTB3
所以对于 JobNumber 12345 6/29 是正确的,但它应该是“这里”而不是“任何地方:
对于 99999,一切都是正确的,但对于 8/1,它应该是“那里”而不是任何地方。这似乎是集合中的中间值。我很混乱。
有谁知道为什么它会抓住这个价值?谢谢你。