人员表
emp_id emp_name sex
1 a 男
2 b 女
3 c 男
4 d 女
得到如下结果:
姓名 性别序号
a 1
b 1
c 2
d 2
其实就是按照性别来生产序号,请问该如何写?
------解决方案--------------------
select emp_name as 姓名,row_number()over(partition by sex order by getdate()) as 性别序号 from tb
------解决方案--------------------
没看出啥规则
------解决方案--------------------
----------------------------------------------------------------
-- Author :fredrickhu(小F,向高手学习)
-- Date :2014-03-26 11:30:49
-- Verstion:
-- Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86)
-- Jul 9 2008 14:43:34
-- Copyright (c) 1988-2008 Microsoft Corporation
-- Enterprise Edition on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
--
----------------------------------------------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([emp_id] int,[emp_name] varchar(1),[sex] varchar(2))
insert [tb]
select 1,'a','男' union all
select 2,'b','女' union all
select 3,'c','男' union all
select 4,'d','女'
--------------开始查询--------------------------
select emp_name as 姓名,row_number()over(partition by sex order by emp_id) as 性别序号 from tb ORDER BY emp_name
----------------结果----------------------------
/* 姓名 性别序号
---- --------------------
a 1
b 1
c 2
d 2
(4 行受影响)
*/
------解决方案--------------------
select emp_name as '姓名',row_number() over(order by emp_id) '性别序号' from 人员表 where sex = '男'
union all
select emp_name as '姓名',row_number() over(order by emp_id) '性别序号' from 人员表 where sex = '女'
------解决方案--------------------
select emp_name,(emp_id-1)/2+1 from tb
------解决方案--------------------
是这样吗:
--drop table t
--go
create table t(emp_id int, emp_name varchar(10),sex varchar(10))
insert into t
select 1 ,'a' ,'男' union all
select 2 ,'b' ,'女' union all
select 3 ,'c' ,'男' union all
select 4 ,'d' ,'女'
go
select *
from
(
select *,
ROW_NUMBER() over(partition by sex order by emp_id) rownum
from t
)t
order by emp_id
/*
emp_id emp_name sex rownum
1 a 男 1
2 b 女 1
3 c 男 2
4 d 女 2
*/
------解决方案--------------------
为什么总是order by getdate() 。难道order by getdate()比 order by 主键快?(我没试过)
怎么看 既然有id,也该用 order by emp_id 吧