注册 登录
编程论坛 SQL Server论坛

关于重复的问题

taoxinhui 发布于 2007-12-12 03:34, 1262 次点击
我现在有个表A
ID  book_name    attorney      price
1   语文             小张               13
2   语文              小李              14
3   数学             小王               15
4   数学             小张               14
我要怎么样实现,让book_name只显示一个,同时后面的attorney,price不消失显示结果要这样
语文    小张     13
       小李     14
数学    小王     15
       小张     14
我这样查询主要是因为ASP里面不要重复名字,能够查询代理人的价格
5 回复
#2
purana2007-12-12 10:17
create table tb(
ID int,
book_name varchar(20),
attorney varchar(20),
price int)

insert tb select 1,'语文','小张',13
insert tb select 1,'语文','小李',14
insert tb select 1,'数学','小王',15
insert tb select 1,'数学','小张',14

select book_name=case when attorney=(select top 1 attorney from tb where book_name=a.book_name) then book_name else '' end,
       attorney,price
from tb a

drop table tb

/*
book_name            attorney             price      
-------------------- -------------------- -----------
语文                小张                   13
                                        小李                   14
数学                小王                   15
                                        小张                   14

(所影响的行数为 4 行)
*/
#3
taoxinhui2007-12-12 13:11
谢谢.可以了啊
#4
happybaby402007-12-12 16:58
select book_name=case when attorney=(select top 1 attorney from tb where book_name=a.book_name) then book_name else '' end,
       attorney,price
from tb a

drop table tb


purana能解释一下这些语句吗/我看到你回的贴子,虽然看到结果了,但是我分析不出来..
#5
西风独自凉2007-12-12 17:14
select book_name,attorney,price  from tb a
這樣應該懂吧,
而這一句:book_name=case when attorney=(select top 1 attorney from tb where book_name=a.book_name) then book_name else '' end
給book_name賦值,當attorney 等於滿足這個語句的返回值 select top 1 attorney from tb where book_name=a.book_name 時 attorney就得於a表中的當前book_name否則就為''(空).
。。。。哎,解釋的不清楚,希望對你有一點幫助。
#6
purana2007-12-12 17:28
嘿嘿..
SQL世界里..
只是告诉它做什么就行.
不需要知道它怎么做.
1