首页 新闻 赞助 找找看

一个sql取样列数据的存储过程

0
悬赏园豆:100 [已解决问题] 解决于 2009-12-04 17:36

设有两张表:tb_user,tb_products 用户表和用户产品表。

用户表的主要结构:tb_user(userid int,userName varchar(20))

产品表的主要结构:tb_products(productID int,productName varchar(20),price numeric(18,2),userid int)

产品表与用户表是多对一关系。

现要从用户表中将所有用户查询出来并显示每个用户的一个产品,这个产品随便是该用户的哪一个都行。

返回表结构如下:

userID   userName   productID   productName   price 

1            张三             54              洗发水               25.6

2            李四             88              香皂                  5.5

.............................

问题补充: 使用的数据库ms sqlserver2000 感谢您的回答。
Handsome Kun的主页 Handsome Kun | 初学一级 | 园豆:100
提问于:2009-11-25 14:30
< >
分享
最佳答案
0
Code
declare @tb_user table(userid int,userName varchar(20))
insert @tb_user
select 1,'张三'
union all
select 2,'李四'


declare @tb_products table(productID int,productName varchar(20),price numeric(18,2),userid int)
insert @tb_products
select 54,'洗发水',25.6,1
union all
select 54,'洗发水1',22.6,1
union all
select 88,'香皂',5.1,2


select identity(int,1,1)id,*
into #temp from @tb_products


select a.userid,username,productid,productName,price
from @tb_user a
left join
(
select * from #temp a where 0=(select count(1) from #temp where productid=a.productid and id<a.id)
)b
on a.userid=b.userid
drop table #temp
收获园豆:80
清海扬波 | 小虾三级 |园豆:825 | 2009-11-25 16:11
综合多人的建议,得到了一个可以解决的比较满意的的方式。 select * from tb_user u inner join ( select * from tb_products where productid in (select max(productid) from tb_products group by userid) ) p on u.userid = p.userid
Handsome Kun | 园豆:100 (初学一级) | 2009-11-25 17:16
我弄的数据有问题,tb_+products 表中ProductId重复了,你这个是可以的。
清海扬波 | 园豆:825 (小虾三级) | 2009-11-25 17:23
select identity(int,1,1)id,* into #temp from @tb_products select a.userid,username,productid,productName,price from @tb_user a left join ( select * from #temp a where 0=(select count(1) from #temp where userid=a.userid and productid<a.productid) )b on a.userid=b.userid drop table #temp 这样就没问题了。
清海扬波 | 园豆:825 (小虾三级) | 2009-11-25 17:26
其他回答(2)
0
故乡的牛 | 园豆:202 (菜鸟二级) | 2009-11-25 17:25
0


SELECT us.*,pd.productName FROM tb_user us
LEFT JOIN tb_products pd ON us.userid = pd.userid
WHERE pd.productName NOT NULL AND pd.productName != ''

收获园豆:20
persialee | 园豆:3217 (老鸟四级) | 2009-11-27 12:53
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册