group by 分组以后我想加一个自通排序的ID 
像 
autoId  name  model  spec 
1        电脑     1 
2        电脑     2 
3        键盘     1 
4        键盘     2 
5        鼠标     1 先根据name,model,spec 分组。。然后加一个 自通排序的ID 大家来讨论这个SQL该咋写 不用临时表越简单。经典更好 两个查询的效果如下: 
2005 查询的效果
select row_number() over (order by inventName) ,inventName,inventCode from t_inventoryinfo group by inventName,inventCode 
1 PCB板 EY-PCB-03 
2 PCB板 EY-PCB-07 
3 PCB板 EY-PCB-09 
4 PCB板 EY-PCB-11 
5 PCB板 EY-PCB-12 
6 PCB板 EY-PCB-14 
7 PCB板 EY-PCB-15 
8 PCB板 EY-PCB-16 
9   PP     Y-BB-301 
10   PP   Y-DB-101 2000 查询的效果
select (select count(*) from t_inventoryinfo a where a.autoId <t_inventoryinfo.autoId) ,inventName,inventCode from t_inventoryinfo group by inventName,inventCode,t_inventoryinfo.autoId 0 油墨 EY-YY-01 
1 音圈 EY-YQ-1373 
2 盆架 EY-PJ-4709 
3 盆架 EY-PJ-2405 
4 盆架 EY-PJ-2403 
5 盆架 EY-SJ-351601 
6 盆架 EY-SJ-251403 
7 磁钢 EY-CG-1301 
8 磁钢 EY-CG-1304 
9 上夹板 EY-SJB-1325 
现在问题是怎么写出:能加自动排序的ID  又不破坏以前排序规则的 SQL语句

解决方案 »

  1.   

    添加一列再用update更新的话不同一般的查询和删除无法指定FROM子句,所以必须用到临时表或表变量
      

  2.   

    UPDATE语句太死板了,似乎无法两表关联更新,做到以下步骤时卡住了
    create table t_inventoryinfo
    (inventName varchar(10),
    inventCode varchar(10)
    )insert into t_inventoryinfo
    select 'PCB板','EY-PCB-03' union all
    select 'PCB板','EY-PCB-07' union all
    select 'PCB板','EY-PCB-09' union all
    select 'PCB板','EY-PCB-11' union all
    select 'PCB板','EY-PCB-12' union all
    select 'PCB板','EY-PCB-14' union all
    select 'PCB板','EY-PCB-15' union all
    select 'PCB板','EY-PCB-16' union all
    select 'PP','Y-BB-301' union all
    select 'PP','Y-DB-101' select row_number() over (order by inventName) as id,inventName,inventCode  into #tmp from t_inventoryinfo group by inventName,inventCode 
      

  3.   

    当然将数据全删掉后再从临时表中取回来的方法可以一试,语句如下truncate table t_inventoryinfoset IDENTITY_INSERT t_inventoryinfo oninsert into t_inventoryinfo (idx,inventName,inventCode) select * from #tmp
      

  4.   

    1. 在7楼的答复是有偷换概念的嫌疑。只是想说,有时候利用中间存储比直接用sql拼凑结果有效。
    2. 表变量是在内存中的; 临时表是在tempdb中的(当然,sqlserver的cache也是有效的),存在磁盘io操作,但也可以建索引。
      

  5.   

    http://blog.csdn.net/fcuandy/archive/2007/04/05/1552710.aspx
    参见连续不重复排名的评论(倒数第二条评论).