SQL查询建议 - 根据重复更新记录

时间:2015-12-05 04:42:47

标签: sql sql-server sql-server-2008

我正在寻求一些建议,我需要编写一个超出我当前SQL技能/能力的查询。

逻辑如下:

对于 SUBQUERY * 中的每组重复devices_fk,请使用最早 date_start值更新行以设置{{ 1}}。每date_end=NOW()只有一条记录,device_fk

子查询:

date_end IS NULL

为了帮助理解我的问题,这就是子查询的输出:

Output of Subquery

执行上述查询后,子查询不应返回任何结果(即,因为没有SELECT map_id, devices_fk, user_fk, date_start, date_end FROM [users_devices_map] WHERE date_end IS NULL AND devices_fk IN (SELECT devices_fk FROM [users_devices_map] WHERE date_end IS NULL GROUP BY devices_fk HAVING COUNT(*) > 1) ORDER BY devices_fk ASC, date_start DESC devices_fk的重复NULL

最终目标是通过为最早的开始设置结束日期(date_end),每个NULL只有一行date_end devices_fk同一设备的日期(date_end)(date_start)。

提前感谢您的时间

2 个答案:

答案 0 :(得分:2)

试试这个 -

;With cteDevicesMap  As
(
      SELECT 
            ROW_NUMBER() OVER (PARTITION BY devices_fk ORDER BY date_start DESC) AS RN
      FROM [users_devices_map]
)
UPDATE [users_devices_map] SET date_end = GETDATE()
FROM cteDevicesMap WHERE RN > 1;

现在检查表格中的记录。

SELECT * FROM [users_devices_map] WHERE date_end IS NULL

答案 1 :(得分:1)

没有测试过这个..

angular.module("tableApp",[]).controller('tableAppCtrl', ['$scope', function($scope) { 
    $scope.titleString="Table Demo"; 
    $scope.selectAllval= false; 
    $scope.setProductTypes= []; 
    $scope.selectAll= function(val){ 
        if(val==false){ 
            $scope.selectAllval= true; 
        } else{ 
            $scope.selectAllval= false; 
        } 
    }; 
    $scope.setProductType= function(type){ 
        $scope.setProductTypes.push(type); 
    }; 
    $scope.prodDataTable = [{ "productType": "A", "productName": "Aaaaaa" }, { "productType": "B", "productName": "Bbbbbb" }, { "productType": "C", "productName": "Cccccc" }]; } ]);