日期:2014-05-19  浏览次数:20357 次

如何取前N条纪录的Sql语句
有3个表
a表:customerid(pk)   customername
          a                               aname
b表:customerid(pk)     addressid(pk)           contactid(pk)         其它字段1
          a                               addr1                             acont1               **
          a                               addr2                             acont2               **
c表:customerid     addressid   其它字段2
          a                       addr1    **
          a                       addr2                 **

如何取得一个新表:   customerid(pk)   customername   addressid       contactid 其它字段1 其它字段2
新表中只有以customerid为主键的一条纪录。


------解决方案--------------------
select top 1 customerid(pk), customername ,addressid , contactid ,其它字段1 ,其它字段2 from a,b,c

------解决方案--------------------
要的結果是?
------解决方案--------------------
貌似c表應該是複合主鍵...

這樣試試

select a.customerid, a.customername, bb.addressid, bb.contactid, bb.其它字段1, cc.其它字段2
from a inner join
(select * from b t
where not exists(select 1 from b
where customerid = t.customerid
and addressid = t.addressid
and contactid = t.contactid
and 其他字段1 < t.其他字段1)) bb
on a.customerid = bb.customerid
inner join
(select * from c t
where not exists(select 1 from c
where customerid = t.customerid
and addressid = t.addressid
and 其他字段2 < t.其他字段2)) cc
on a.customerid = cc.customerid
------解决方案--------------------

-- sql 2005 做这事就容易了

SELECT
*
FROM A
OUTER APPLY(
SELECT TOP 1
addressid, contactid, 其它字段1
FROM B
WHERE A.customerid = B.customerid
)B
OUTER APPLY(
SELECT TOP 1
其它字段2
FROM C
WHERE A.customerid = C.customerid
)C