请帮我创建一个SQL查询

时间:2010-01-23 05:09:22

标签: sql sql-server

我有以下3个表

CREATE TABLE [dbo].[dspartner](
[dspartnerid] [bigint] IDENTITY(1,1) NOT NULL,
[name] [varchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[priority] [int] NULL)

CREATE TABLE [dbo].[hotels](
[hotelid] [int] PRIMARY KEY  IDENTITY(1,1) NOT NULL,
[name] [varchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[DSPartnerid] [bigint] NULL,
)

CREATE TABLE [HotelSourceMap](
[hotelsourcemapid] [bigint] PRIMARY KEY  IDENTITY(1,1) NOT NULL,
[dspartnerid] [bigint] NOT NULL,
[hotelid] [bigint] NOT NULL,
    [dshotelid] bigint
)

情况是这样的:

我想要表:dspartner包含有关数据源合作伙伴的详细信息。 表:酒店包含酒店的详细信息 table:HotelSourceMap包含hotels.hotelid,dsparnter.dspartnerid

的记录

new我想更新酒店表,以便设置hotels.hdspartner = hotelsourcemap.dspartnerid 哪里 hotels.hotelid = hotelsourcemap.hotelid 和hotelsourcemap.dspartnerid = dspartner.dspartnerid(其中dspartnerid的priorirty很高)

注意:-priority包含int值,max int值将被视为最高优先级。如果两个dspartner具有相同的优先级,则获取其中任何一个

sql server 2005

1 个答案:

答案 0 :(得分:1)

使用:

UPDATE HOTELS
   SET dspartners = (SELECT x.dspartnerid
                       FROM (SELECT hsm.dspartnerid,
                                    ROW_NUMBER() OVER(PARTITION BY hsm.hotelid 
                                                      ORDER BY p.priority, p.name DESC) AS rank
                               FROM HOTELSOURCEMAP hsm
                               JOIN DSPARTNER p ON p.dspartnerid = hsm.dspartnerid
                              WHERE hsm.hotelid = hotelid) x
                      WHERE x.rank = 1)

为了确保工作正常,请运行:

SELECT x.dspartnerid
  FROM (SELECT hsm.dspartnerid,
               ROW_NUMBER() OVER(PARTITION BY hsm.hotelid 
                                 ORDER BY p.priority, p.name DESC) AS rank
          FROM HOTELSOURCEMAP hsm
          JOIN DSPARTNER p ON p.dspartnerid = hsm.dspartnerid
         WHERE hsm.hotelid = ?) x
 WHERE x.rank = 1

?替换为您选择的任何hotelid 即使有多个dspartnerid具有相同的高优先级,它也只会返回一个dspartnerid值。