我的下面的查詢工作正常,它根據最新的掃描將新產品註冊到不同的位置。SQL「分區」檢查工作不正常
我的問題是,有時我收到的產品具有相同的ID(這實際上是可能的)。 在我的波紋管表中,通常當產品到達位置5這意味着它已完成,並且當新產品獲得註冊時,它始終始於位置1。 正如你可以看到下面我再次得到了產品「2222」,我想我的下面「FirstScanned」檢索2222',1,'2017-05-17 15:58而不是2222',1 「2017年3月21日09:50
,min(p.Scanned) over (partition by p.ProductNR) as FirstScanned
表:
CREATE TABLE Products
(
ProductNR varchar (14),
Location int,
Scanned Datetime
);
Insert Into Products(ProductNR, Location, Scanned)
Values('1111', 1, '2017-03-15 09:30'),
('1111', 2, '2017-03-16 11:35'),
('1111', 3, '2017-03-21 12:37'),
('2222', 1, '2017-03-21 09:50'),
('2222', 5, '2017-03-21 12:58');
('2222', 1, '2017-05-17 15:58');
和查詢
select p.ProductNR, p.Location, p.Scanned
,case
when p.FirstScanned >= dateadd(day, -5, getdate()) then 'Less than 5 days old'
when p.FirstScanned <= dateadd(day, -5, getdate()) then 'More than 5 days old'
else '0'
end as Age
from
(
select p.ProductNR
,p.Location
,p.Scanned
,min(p.Scanned) over (partition by p.ProductNR) as FirstScanned
,max(p.Scanned) over (partition by p.ProductNR) as LastScanned
from Products p
) p
where p.LastScanned = p.Scanned
加1爲測試數據,同時也加上預期的結果和實際結果 – TheGameiswar
謝謝!我期望的基本上是,如果一個新的產品註冊到我的表中已經有相同的productnr。我想我的查詢只檢索新的,而不是舊的。舊的通常被定義爲位置5關閉,正如我上面所解釋的那樣,日期也是老的 – MishMish
對於1111,輸出是什麼?由於位置5沒有記錄,因此沒有選擇記錄? –