2

我在 SQL Server 2008 中有如下表

  AMID                TierLevel
 --------            -------------
  999                 GOLD
  1000                SILVER   
  1000                GOLD
  1000                PLATINUM
  1000                BRONZE
  1001                GOLD
  1001                SILVER
  1002                SILVER
  1003                GOLD

现在我想像下面这样更新这个表

  AMID                TierLevel
 --------            -------------
  999                 GOLD
  1000               PLATINUM  
  1000               PLATINUM
  1000               PLATINUM
  1000               PLATINUM
  1001                GOLD
  1001                GOLD
  1002                SILVER
  1003                GOLD

这里的条件是

  • 我想要同一个 AMID 的唯一层级值,并且层级值应该在优先级基础中选择,例如

    1. 金子
    2. 青铜
  • 这意味着如果它的等级值中存在最高的等级,则选择该等级。就像我在第二张表中显示的那样,白金代表 1000,黄金代表 1001..

请在这件事上给予我帮助

谢谢,
哈利

4

2 回答 2

2
DECLARE @amid TABLE (Amid INT, TierLevel VARCHAR(20));

INSERT @amid VALUES
(999 ,'GOLD'),
(1000,'SILVER'), (1000,'GOLD'),   (1000,'PLATINUM'), (1000,'BRONZE'),
(1001,'GOLD'),   (1001,'SILVER'),
(1002,'SILVER'), (1003,'GOLD');

;WITH [priority](r, n) AS
(
    SELECT 1, 'PLATINUM'
    UNION ALL SELECT 2, 'GOLD'
    UNION ALL SELECT 3, 'SILVER'
    UNION ALL SELECT 4, 'BRONZE'
),
per_amid(amid, h) AS
(
    SELECT a.amid, MIN(p.r)
      FROM @amid AS a
      INNER JOIN [priority] AS p
      ON a.TierLevel = p.n
      GROUP BY a.amid
)
UPDATE a
  SET TierLevel = p.n
  FROM @amid AS a
  INNER JOIN per_amid AS pa
  ON a.Amid = pa.amid
  INNER JOIN [priority] AS p
  ON pa.h = p.r
  -- added where clause to address question brought up on other answer
  WHERE a.TierLevel <> p.n;

SELECT Amid, TierLevel FROM @amid;

结果:

Amid  TierLevel
----  ---------
999   GOLD
1000  PLATINUM
1000  PLATINUM
1000  PLATINUM
1000  PLATINUM
1001  GOLD
1001  GOLD
1002  SILVER
1003  GOLD
于 2012-05-21T15:33:49.747 回答
1

我会使用一个临时表来存储每个层的等级:

DECLARE @Rank TABLE (ID INT NOT NULL PRIMARY KEY, Name VARCHAR(10) NOT NULL)
INSERT @Rank VALUES (1, 'PLATINUM'), (2, 'GOLD'), (3, 'SILVER'), (4, 'BRONZE')

;WITH T AS
(   SELECT  AMID, TierLevel, MIN(ID) OVER(PARTITION BY AMID) [MinID]
    FROM    #T
            INNER JOIN @Rank
                ON Name = TierLevel
)
UPDATE  T
SET     TierLevel = Name
FROM    T
        INNER JOIN @Rank
            ON ID = MinID
WHERE   TierLevel <> Name

这是使用以下示例数据完成的:

CREATE TABLE #T (AMID INT, TierLevel VARCHAR(10))
INSERT #T VALUES 
    (999, 'GOLD'), 
    (1000, 'SILVER'), 
    (1000, 'GOLD'), 
    (1000, 'PLATINUM'), 
    (1000, 'BRONZE'),
    (1001, 'GOLD'),
    (1001, 'SILVER'),
    (1002, 'SILVER'),
    (1003, 'GOLD')
于 2012-05-21T15:25:03.080 回答