2

这是我的带有示例数据的表。

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吗?

4

6 回答 6

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

这是一个带有查询的 SQLFiddle

于 2013-10-24T11:33:12.420 回答
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)
于 2013-10-24T11:17:56.790 回答
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;
于 2013-10-24T11:24:25.720 回答
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
于 2013-10-24T11:24:52.073 回答
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;
于 2013-10-24T11:24:59.800 回答
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) 
于 2013-10-24T11:49:04.387 回答