0

我英语不好……请帮帮我……在SQL Server 2005,我有一张表Total(PhoneNumber, Money, City) ,有许多相同的记录,但具有相同PhoneNumber但不同CityMoney值。现在我想NewCity通过以下方式为列设置值:(select Max Money记录中具有相同的最大金额PhoneNumber)在记录中。我怎样才能做到这一点?请帮帮我……</p>

例如:

PhoneNumber  City   Money   NewCity
0949000000   CTA    20      NULL
0945777777   VTH    35      NULL
0949000000   VTH    30      NULL
0945777777   VTY    120     NULL
0949000000   VTY    60      NULL
4

3 回答 3

1

假设您要设置NewCity为带有forCity的行所具有的值。(而不是数字)Max(Money)PhoneNumberMax(Money)

;WITH T1 AS
(
SELECT *,
       ROW_NUMBER() OVER (PARTITION BY PhoneNumber 
                              ORDER BY Money DESC) AS RN
FROM YourTable       
), T2 AS
(
SELECT *,
       MAX(CASE WHEN RN = 1 THEN City END) 
                 OVER (PARTITION BY PhoneNumber) AS _NewCity
FROM T1       
)
UPDATE T2
SET NewCity = _NewCity

如果我的假设是错误的,并且您实际上确实想要问题所陈述的内容,那么这会更简单。

;WITH CTE
     AS (SELECT *,
                MAX(money) OVER (partition BY PhoneNumber) Mx
         FROM   YourTable)
UPDATE CTE
SET    NewCity = Mx 
于 2013-06-26T09:30:21.373 回答
0

请试试:

update t 
set NewCity=(select MAX(money) from YourTable b where b.PhoneNumber=t.PhoneNumber)
from  YourTable t
于 2013-06-26T09:25:55.860 回答
0

如果您的总表中没有 newcity 列,并且只查看总表上的 max(money) 和重复表上的分组依据,您可以尝试这个来查看 newcity 列。

select a.*,b.newcity from total a
join (select phonenumber,city, max(money) as newcity
      from total group by phonenumber,city) b on b.phonenumber = a.phonenumber 
                                            and b.city = a.city
where a.money = b.newcity
于 2013-06-26T09:49:17.990 回答