基于第二个字段的SQL重复行

时间:2016-02-18 17:07:02

标签: sql-server

我有一个包含四列的表格。当存在重复的启动时间值时,我需要显示具有最新(最新)插入值的行。在下面的示例中,前两行具有相同的启动时间值。我想显示插入值为“2016-02-07 10:45:00”的行,因为它具有重复行的后期(较新)日期和时间。我需要为整个表格而不仅仅是一行。先感谢您。我真的被卡住了。

Table Image

3 个答案:

答案 0 :(得分:2)

使用ROW_NUMBER可能是最简单的方法。

<?php
header ('Content-Type: image/png');
$url = "https://www.google.co.uk/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";

list($width, $height, $type, $attr) = getimagesize($url);
$source = imagecreatefrompng($url);
$image = imagecreatetruecolor($width, $height);
imagefilledrectangle($image, 0, 0, $width-1, $height-1, imagecolorallocatealpha($image, 255,255,255,0));
//fill with white rectangle to look transparent, but note that it isn't. Changing alpha channel merely shows
//a black background.

for ($x = 0;$x<$width;$x++){
    for ($y = 0;$y<$height;$y++){
        $rgb = imagecolorat($source, $x,$y);
        $r = ($rgb >> 16) & 0xFF;
        $g = ($rgb >> 8) & 0xFF;
        $b = $rgb & 0xFF;
        $colors = imagecolorsforindex($image, $rgb);
        imagesetpixel($image,$x,$y,imagecolorallocatealpha($image,$colors["red"],$colors["green"],$colors["blue"],$colors["alpha"]));
        //getting alpha from pixels for a real 'copy'
    }
}

imagepng($image);
imagedestroy($image);
imagedestroy($source);
?>

SQL Fiddle Demo

答案 1 :(得分:0)

你可以这样做:

SELECT DriverID
      ,Activity
      ,StartTime
      ,MAX(InsertTS) as InsertTS
      ,MAX(Duration) as Duration
FROM TableName
GROUP BY DriverID, Activity, StartTime

这假设当存在重复时,持续时间会更长。如果情况并非如此,您可以将其用作自我加入:

SELECT t1.* 
FROM TableName t1
INNER JOIN (
    SELECT DriverID
          ,Activity
          ,StartTime
          ,MAX(InsertTS) as InsertTS
    FROM TableName
    GROUP BY DriverID, Activity, StartTime) t2
ON t1.DriverID = t2.DriverID 
   AND t1.Activity = t2.Activity 
   AND t1.StartTime = t2.StartTime 
   AND t1.InsertTS = t2.InsertTS

答案 2 :(得分:0)

CTEWindowed functions可以使这更清洁。

WITH [Expanded] AS (
    SELECT 
        DriverID
        ,Activity
        ,StartTime
        ,InsertTS
        ,Duration
        ,MAX(InsertTS) OVER (PARTITION BY DriverID, Activity, StartTime) as InsertTS_Max
        ,MAX(Duration) OVER (PARTITION BY DriverID, Activity, StartTime) as Duration_Max
    FROM TableName
)
    SELECT *
    FROM [Expanded]
    WHERE
        InsertTS = InsertTS_Max