我有示例数据
Name Product Prd_cnt Prd_dt
BSA CYCLE 20 29-01-2019
BSA CYCLE 20 28-01-2019
BSA CYCLE 20 27-01-2019
BSA CYCLE 20 26-01-2019
BSA CYCLE 40 25-01-2019
BSA CYCLE 35 24-01-2019
BSA CYCLE 35 23-01-2019
BSA CYCLE 35 22-01-2019
即使日期不同,我也需要选择最近4天具有相同计数的记录。从当前日期到过去4天。如果其中一个记录与最近4天不同。不需要那些记录。
输出:
Name Product Prd_cnt Prd_dt
BSA CYCLE 20 29-01-2019
BSA CYCLE 20 28-01-2019
BSA CYCLE 20 27-01-2019
BSA CYCLE 20 26-01-2019
我尝试使用ROW_NUMBER
并拥有COUNT()
。
答案 0 :(得分:0)
只需使用BETWEEN
和DATEADD()
来查找最近4天的结果:
SELECT * FROM YourTable
WHERE PRD_DT BETWEEN CAST(DATEADD(DAY,-3,GETDATE()) AS DATE)
AND CAST(GETDATE() AS DATE)
答案 1 :(得分:0)
我只会使用exists
。
首先,创建并填充示例表(请在您将来的问题中为我们保存此步骤):
CREATE TABLE T(
Name VARCHAR(50),
Product VARCHAR(50),
Prd_cnt INT,
Prd_dt DATE
);
INSERT INTO T (Name, Product, Prd_cnt, Prd_dt) VALUES
('BSA','CYCLE',20,'2019-01-29'),
('BSA','CYCLE',20,'2019-01-28'),
('BSA','CYCLE',20,'2019-01-27'),
('BSA','CYCLE',20,'2019-01-26'),
('BSA','CYCLE',40,'2019-01-25'),
('BSA','CYCLE',35,'2019-01-24'),
('BSA','CYCLE',35,'2019-01-23'),
('BSA','CYCLE',35,'2019-01-22'),
('BSA','CYCLE',40,'2019-01-21');
然后是一个简单的公用表表达式和一个存在的子查询:
WITH CTE AS
(
SELECT Name,Product,Prd_cnt,Prd_dt
FROM T As t0
WHERE Prd_dt <= GETDATE()
AND Prd_dt >= CAST(DATEADD(DAY, -3, GETDATE()) As Date)
)
SELECT Name,Product,Prd_cnt,Prd_dt
FROM CTE As t0
WHERE EXISTS
(
SELECT 1
FROM CTE As t1
WHERE t0.Prd_dt <> t1.Prd_dt
AND t0.Prd_cnt = t1.Prd_cnt
)
公用表表达式会选择最近四天的所有记录,而exist仅过滤具有重复Prd_cnt值的记录。
请注意,如果您想让重复项也考虑其他列,您要做的就是将它们添加到exist子查询where子句中。
感谢D-Shih为DDL + DML样本数据创建小提琴。
答案 2 :(得分:0)
您可以尝试
SELECT distinct Orders.*
FROM (
SELECT Name, Product, Prd_cnt, ROW_NUMBER ()
OVER (PARTITION BY Name, Product, Prd_cnt order by Prd_dt) as RN
FROM Orders
)t
inner join Orders on t.Name = Orders.Name and t.Prd_cnt = Orders.Prd_cnt
and t.Product = Orders.Product where RN >= 4 AND Orders.Prd_dt < GetDate()
答案 3 :(得分:0)
请尝试以下查询:
select * from myTable t1
where Prd_dt > cast(dateadd(day, -4, getdate()) as date)
and exists(select 1 from myTable
where Prd_dt > cast(dateadd(day, -4, getdate()) as date)
and product = t1.product
group by product
having count(*) > 1)
如果特定的Product
有两个以上的记录,则子查询将返回行,这又将产生所有行,并且在最近四天内重复了Product
的值。
答案 4 :(得分:0)
您可以尝试
SELECT * FROM T WHERE Prd_cnt=(SELECT Prd_cnt FROM T HAVING COUNT(Prd_cnt)>1) and
DATEDIFF(CURRENT_TIMESTAMP,(
SELECT Prd_dt FROM T WHERE DATEDIFF(CURRENT_TIMESTAMP,Prd_dt)<4 ORDER BY Prd_dt LIMIT 1));