SQL 自增长列

苦逼的程序员 2011-09-13 11:30:25
比如查询用户留言行数
SELECT neirong,liuyanren FROM message
显示的是
neirong liuyanren
AA 张三
BB 张三
AA 李四
BB 李四
AA 王五
BB 王五
现在我想通过SQL,查询的时候加一列序号列,根据人名分组自增加
显示成:
xuhao neirong liuyanren
1 AA 张三
2 BB 张三
1 AA 李四
2 BB 李四
1 AA 王五
2 BB 王五
请问SQL该怎么写


...全文
73 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
苦逼的程序员 2011-09-13
  • 打赏
  • 举报
回复
谢谢大家:)
--小F-- 2011-09-13
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 wufeng4552 的回复:]
引用 5 楼 fredrickhu 的回复:
SQL code

---2000的
select
xuhao=(select count(distinct liuyanren)+1 from message where neirong=t.neirong),*
from
message t

F姐姐
反了
[/Quote]
是的 反了 还掉了
--小F-- 2011-09-13
  • 打赏
  • 举报
回复
----------------------------------------------------------------
-- Author :fredrickhu(小F,向高手学习)
-- Date :2011-09-13 11:38:25
-- Verstion:
-- Microsoft SQL Server 2008 R2 (RTM) - 10.50.1617.0 (Intel X86)
-- Apr 22 2011 11:57:00
-- Copyright (c) Microsoft Corporation
-- Enterprise Evaluation Edition on Windows NT 6.1 <X64> (Build 7600: ) (WOW64)
--
----------------------------------------------------------------
--> 测试数据:[message]
if object_id('[message]') is not null drop table [message]
go
create table [message]([neirong] varchar(2),[liuyanren] varchar(4))
insert [message]
select 'AA','张三' union all
select 'BB','张三' union all
select 'AA','李四' union all
select 'BB','李四' union all
select 'AA','王五' union all
select 'BB','王五'
--------------开始查询--------------------------
select
xuhao=(select count(distinct neirong)+1 from message where liuyanren=t.liuyanren and neirong<t.neirong),*
from
message t
----------------结果----------------------------
/* xuhao neirong liuyanren
----------- ------- ---------
1 AA 张三
2 BB 张三
1 AA 李四
2 BB 李四
1 AA 王五
2 BB 王五

(6 行受影响)
*/
水族杰纶 2011-09-13
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 fredrickhu 的回复:]
SQL code

---2000的
select
xuhao=(select count(distinct liuyanren)+1 from message where neirong=t.neirong),*
from
message t
[/Quote]
F姐姐
反了
--小F-- 2011-09-13
  • 打赏
  • 举报
回复
---2000的
select
xuhao=(select count(distinct liuyanren)+1 from message where neirong=t.neirong),*
from
message t
chuanzhang5687 2011-09-13
  • 打赏
  • 举报
回复
+1[Quote=引用 1 楼 wufeng4552 的回复:]
SQL code
xuhao=row_number()over(partition by liuyanren order by neirong)
[/Quote]
NBDBA 2011-09-13
  • 打赏
  • 举报
回复
SELECT row_number() over(PARTITION BY liuyanren order by getdate()) as xuhao 
,neirong,liuyanren FROM message
NBDBA 2011-09-13
  • 打赏
  • 举报
回复
SELECT row_number() over(PARTITION BY neirong order by getdate()) as xuhao 
,neirong,liuyanren FROM message
水族杰纶 2011-09-13
  • 打赏
  • 举报
回复
xuhao=row_number()over(partition by liuyanren order by neirong)

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧