结果:
id name count(distinct name)
1 a 1
2 b 1
3 c 1
方法二
表 table1
id regname postionsn personsn
1 山东齐鲁制药 223 2
2 山东齐鲁制药 224 2
3 北京城建公司 225 2
4 科技公司 225 2
我想获得结果是
id regname postionsn personsn
1 山东齐鲁制药 223 2
3 北京城建公司 225 2
4 科技公司 225 2
如果查询的是多列 distinct 用和不用一样
只能用group by
用group by regname
实例三
个人成绩表:
学号 课号 成绩
01 01 80
01 02 79
01 03 88
02 01 87
02 02 77
02 03 68
用sql把上表转换为:
学号 课号01 课号02 课号03
01 80 79 88
02 87 77 68
---------建表----------
create table tab_score
(
bid int identity(0,1) primary key ,--流水号
sid varchar(20) not null,--学生号
cid varchar(20) not null,--课程号
score int--成绩
)
insert into tab_score select's01','c01','90' union all select 's01','c02','92' union all select 's01','c03','93'
union all select 's02','c01','81' union all select 's02','c02','82'
/*---固定列的写法,后面的写法将是根据有几个课程id来动态组装中间的sum语句,然后加上头尾就成了,
理解了这种'静态'写法,剩下的只是'动态'组装中间sum语句的工作----*/
-----'动态'列的写法,定义一个变量来组装中间的sum语句,其中用到子查询表(原来不用这方法一直会出现重复列)-------