一、表:
1、商品分类表(type),
字段
id name
1 吃头
2 玩具2、商品表(product),
字段
id type_id name shelf_time
id 分类 商品名 上架时间1 1 白糖 2012-12-01
2 1 红糖 2012-12-09
3 2 痒痒挠 2012-12-08
4 4 挠痒痒 2012-12-07二、需求:
要根据商品分类进行分组,每组按照上架时间倒叙排列,各组之间再按照最新上架的一个商品记录进行排序。(也就是同一类商品需要是挨着的)。最终出来的结果集应该是:2 1 红糖 2012-12-09
1 1 白糖 2012-12-01
3 2 痒痒挠 2012-12-08
4 4 挠痒痒 2012-12-07这个SQL咋写? 多谢各位~~
1、商品分类表(type),
字段
id name
1 吃头
2 玩具2、商品表(product),
字段
id type_id name shelf_time
id 分类 商品名 上架时间1 1 白糖 2012-12-01
2 1 红糖 2012-12-09
3 2 痒痒挠 2012-12-08
4 4 挠痒痒 2012-12-07二、需求:
要根据商品分类进行分组,每组按照上架时间倒叙排列,各组之间再按照最新上架的一个商品记录进行排序。(也就是同一类商品需要是挨着的)。最终出来的结果集应该是:2 1 红糖 2012-12-09
1 1 白糖 2012-12-01
3 2 痒痒挠 2012-12-08
4 4 挠痒痒 2012-12-07这个SQL咋写? 多谢各位~~
解决方案 »
- oracle的安装问题
- 关于aa<=to_Date('20120731','yyyymmdd')的问题
- 登陆PLSQL后总是报ORA-12154:TNS:could not resolve the connect identifier specified。
- oracle imp问题
- 请教:Merge语句的WHEN子句中可否使用条件判断?
- 请教2个sql文
- JDBC连接oracle问题
- Excel 表格怎么导入Oracle数据库和Sql server数据库
- 小弟用proc程序select或update时中文字段显示乱码,请问哪位大虾能指点!!!???
- 请教,大家用什么语言和工具制作网站查询oracle数据库??
- 我发现oracle的一个问题, 关于序列的,求解决
- ORA-04044该怎么解决呢?谢谢
partition by之后,后面的order by 只是对分组内的数据进行的排序。
1 1 白糖 2012-12-01
2 1 红糖 2012-12-09
3 2 痒痒挠 2012-12-08
4 2 挠痒痒 2012-12-07
5 2 ABC 2012-12-17
6 2 DEF 2012-12-15要的效果为:
5 2 ABC 2012-12-17
6 2 DEF 2012-12-15
3 2 痒痒挠 2012-12-08
4 2 挠痒痒 2012-12-072 1 红糖 2012-12-09
1 1 白糖 2012-12-01
附初始化测试数据:
CREATE TABLE product (
id int NOT NULL,
type_id int DEFAULT NULL,
name varchar(20) DEFAULT NULL,
shelf_time date DEFAULT NULL,
PRIMARY KEY (id)
);INSERT INTO product VALUES ('1', '1', '白糖', '2012-12-01');
INSERT INTO product VALUES ('2', '1', '红糖', '2012-12-09');
INSERT INTO product VALUES ('3', '2', '痒痒挠', '2012-12-08');
INSERT INTO product VALUES ('4', '2', '挠痒痒', '2012-12-07');
INSERT INTO product VALUES ('5', '2', 'abc', '2012-12-17');
INSERT INTO product VALUES ('6', '2', 'def', '2012-12-15');
这样不行?
SQL> select t.*,row_number() over (partition by type_id order by shelf_time desc) from product t;
ID TYPE_ID NAME SHELF_TIME ROW_NUMBER()OVER(PARTITIONBYTY
-------------------------------
2 1 红糖 2012/12/9 1
1 1 白糖 2012/12/1 2
5 2 abc 2012/12/17 1
6 2 def 2012/12/15 2
3 2 痒痒挠 2012/12/8 3
4 2 挠痒痒 2012/12/7 4
6 rows selected
SQL>
select product.*,
max(shelf_time) over (partition by type_id) as latest_shelf_time
from product
) order by latest_shelf_time desc, type_id, shelf_time desc;
from product t
order by type_id desc, s desc;
这次好吧
name,
max(shelf_time) over(order by shelf_time)
from product
order by max(type_id) over(partition by type_id) desc,
max(shelf_time) over(order by shelf_time) desc倒序排列 与答案一模一样 给分
SELECT * FROM product t
ORDER BY t.type_id DESC, t.shelf_time DESC
这就可以了