这是我的表格,包含样本数据。
id | path | category (1-6) | secter_id | date
----------------------------------------------
1 | ddd | 5 | a | 10-01
2 | ddgg | 6 | a | 10-03
3 | fff | 5 | a | 10-02
我想过滤每个扇区ID的最新类别5和6行。
预期结果
id path | category| secter_id | date
--------------------------------------
2 | ddgg | 6 | a | 10-03
3 | fff | 5 | a | 10-02
这可能只做sql吗?
答案 0 :(得分:2)
此查询应该为您执行
SELECT A.ID,
A.PATH,
A.CATEGORY,
A.SECTOR_ID,
A.dDATE
FROM yourTable A
INNER JOIN
(SELECT CATEGORY,
MAX(dDate) AS dDate
FROM yourTable
GROUP BY CATEGORY) B
ON A.CATEGORY = B.CATEGORY
AND A.dDate = B.dDate
答案 1 :(得分:0)
您可以尝试使用此代码,但不是很优雅但它应该可以正常工作。
Select id,path,category,secter_id,date
FROM myTable a
INNER JOIN (SELECT category, MAX(date) date FROM myTable GROUP BY Category) b ON a.category = b.Category AND a.date = b.Date
WHERE A.Category IN (5,6)
答案 2 :(得分:0)
你可以试试这个 -
SELECT id,path,category,secter_id, date
FROM
(
SELECT id,path,category,secter_id, date,
DENSE_RANK() OVER (PARTITION BY category ORDER BY DATE DESC) date_rank
FROM sample_table t
WHERE category in (5,6)
)
WHERE date_rank = 1;
答案 3 :(得分:0)
试试这个
select path,category,secter_id,date from
(
select path,category,secter_id,date,dense_rank() over(PARTITION by category order by date desc)as rk
from tbl WHERE category in (5,6)
)data
where rk=1
答案 4 :(得分:0)
select * from (
select
id, path , category, secter_id, date ,
row_number() over (partition by category order by date desc) as rnk
from your_table
)
where rnk = 1;
答案 5 :(得分:0)
试试这个
SELECT [id]
,[path]
,[category]
,[secter_id]
,[date]
FROM [MyTable]
WHERE date IN (SELECT MAX(date)
FROM [MyTable]
WHERE category IN (SELECT DISTINCT category FROM MyTable)
GROUP BY category)