Sql需要帮助进行更新查询

时间:2014-03-21 09:45:32

标签: sql

我需要帮助。我有每个用户包含1或2行的表。看起来像

| UserId | CreateOn   | order | 
|-----------------------------|
| 1      | 2014-01-01 | NULL  | 
|--------|------------|-------|
| 1      | 2014-01-02 | NULL  | 
|--------|------------|-------|
| 2      | 2014-02-01 | NULL  |
|--------|------------|-------|
| 2      | 2014-02-02 | NULL  |
|--------|------------|-------|
| 3      | 2014-03-01 | NULL  |

我需要通过createOn为每个userId

设置1或2依赖的顺序

编辑:我使用Ms Sql Server 我尝试这样的事情

UPDATE table1
SET Order = 1
WHERE UserId = 1 AND CreatedOn > (
                SELECT TOP 1 t2.CreatedOn 
                FROM table2 t2
                WHERE t2.UserId = 1
                ORDER BY t2.CreatedOn DESC)

但它仅适用于1行

Edit2:结果必须如

| UserId | CreateOn   | order | 
|-----------------------------|
| 1      | 2014-01-01 | 1  | 
|--------|------------|-------|
| 1      | 2014-01-02 | 2  | 
|--------|------------|-------|
| 2      | 2014-02-01 | 1  |
|--------|------------|-------|
| 2      | 2014-02-02 | 2  |
|--------|------------|-------|
| 3      | 2014-03-01 | 1  |

2 个答案:

答案 0 :(得分:3)

如果我忘了你,你可以在SQL Server中使用窗口(over()子句)和公用表表达式来实现它:

create table #test(userid int,CreateOn date,[order] int);

insert into #test(userid,CreateOn) VALUES
    (1,'2014-01-01'),
    (1,'2014-01-02'),
    (2,'2014-02-01'),
    (2,'2014-02-02'),
    (3,'2014-03-01');

with testCTE as (   
    select userid,CreateOn,ROW_NUMBER() over(partition by userid order by createon) as NewOrder
    from #test
)
update t
set [order] = tc.NewOrder
from #test t 
join testCTE tc on tc.userid = t.userid
    and tc.CreateOn = t.CreateOn

select * from #test

这将得到如下结果:

userid      CreateOn   order
1           2014-01-01 1
1           2014-01-02 2
2           2014-02-01 1
2           2014-02-02 2
3           2014-03-01 1

答案 1 :(得分:0)

Oracle版本:

merge into the_table
using
(
    select rowid as rid,
           row_number() over (partition by userid order by createon) as rn
    from the_table
) t on (t.rid = the_table.rowid) 
when matched then 
   set "order" = rn;

Postgres版本:

with numbered as (
  select ctid as cid,
         row_number() over (partition by userid order by createon) as rn
  from the_table
)
update the_table
  set "order" = rn
from numbered
where numbered.cid = the_table.ctid;