当前位置:  开发笔记 > 数据库 > 正文

Sql Server查询选择Top和分组依据

如何解决《SqlServer查询选择Top和分组依据》经验,为你挑选了1个好方法。

SpousesTable SpouseID

SpousePreviousAddressesTable PreviousAddressID,SpouseID,FromDate,AddressTypeID

我现在所拥有的是更新整个表的最新版本并分配最新的,无论SpouseID是AddressTypeID = 1

我想为SpousePreviousAddresses表中的每个唯一SpouseID分配最新的SpousePreviousAddress.AddressTypeID = 1.

UPDATE spa 
SET spa.AddressTypeID = 1
FROM SpousePreviousAddresses AS spa INNER JOIN Spouses ON spa.SpouseID = Spouses.SpouseID,
(SELECT TOP 1 SpousePreviousAddresses.* FROM SpousePreviousAddresses 
    INNER JOIN Spouses AS s ON SpousePreviousAddresses.SpouseID = s.SpouseID 
    WHERE SpousePreviousAddresses.CountryID = 181 ORDER BY SpousePreviousAddresses.FromDate DESC) as us
WHERE spa.PreviousAddressID = us.PreviousAddressID

我想我需要一个小组,但我的sql并不是那么热门.谢谢.

正在运行的更新

我之前找到了解决方案的错误.以下是我要解决的问题

WITH result AS
(
    SELECT ROW_NUMBER() OVER (PARTITION BY SpouseID ORDER BY FromDate DESC) AS rowNumber, *
    FROM SpousePreviousAddresses
    WHERE CountryID = 181
)
UPDATE result
SET AddressTypeID = 1
FROM result WHERE rowNumber = 1

jheppinstall.. 5

假设您正在使用SQLServer 2005(基于您从上一次尝试获得的错误消息)可能最直接的方法是使用ROW_NUMBER()函数与Common Table Expression一起使用,我想这可能会对您有所帮助正在找:

WITH result AS
(
SELECT 
    ROW_NUMBER() OVER (PARTITION BY SpouseID ORDER BY FromDate DESC) as rowNumber,
    * 
FROM 
    SpousePreviousAddresses
)
    UPDATE SpousePreviousAddresses
    SET
        AddressTypeID = 2
    FROM 
        SpousePreviousAddresses spa
            INNER JOIN result r ON spa.SpouseId = r.SpouseId
    WHERE r.rowNumber = 1
            AND spa.PreviousAddressID = r.PreviousAddressID
            AND spa.CountryID = 181

在SQLServer2005中,ROW_NUMBER()函数是最强大的函数之一.它在很多情况下非常有用.学习它的时间将多次重新支付.

CTE用于简单地修改代码abit,因为它不需要某种临时表来存储itermediate结果.

生成的查询应该快速有效.我知道CTE中的select使用*,这有点过分,因为我们不需要所有列,但如果有人想看看查询中发生了什么,它可能有助于显示正在发生的事情.



1> jheppinstall..:

假设您正在使用SQLServer 2005(基于您从上一次尝试获得的错误消息)可能最直接的方法是使用ROW_NUMBER()函数与Common Table Expression一起使用,我想这可能会对您有所帮助正在找:

WITH result AS
(
SELECT 
    ROW_NUMBER() OVER (PARTITION BY SpouseID ORDER BY FromDate DESC) as rowNumber,
    * 
FROM 
    SpousePreviousAddresses
)
    UPDATE SpousePreviousAddresses
    SET
        AddressTypeID = 2
    FROM 
        SpousePreviousAddresses spa
            INNER JOIN result r ON spa.SpouseId = r.SpouseId
    WHERE r.rowNumber = 1
            AND spa.PreviousAddressID = r.PreviousAddressID
            AND spa.CountryID = 181

在SQLServer2005中,ROW_NUMBER()函数是最强大的函数之一.它在很多情况下非常有用.学习它的时间将多次重新支付.

CTE用于简单地修改代码abit,因为它不需要某种临时表来存储itermediate结果.

生成的查询应该快速有效.我知道CTE中的select使用*,这有点过分,因为我们不需要所有列,但如果有人想看看查询中发生了什么,它可能有助于显示正在发生的事情.

推荐阅读
农大军乐团_697
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有