选择最新记录的最佳方式

时间:2017-05-05 00:20:02

标签: sql-server database row-number partition-by

因此我使用的数据库没有很好的方法来通过其唯一ID选择最新的数字。我们必须缩小以获得最新记录,其中一组子查询加入到原始表中。原始表是TBL_POL。 实施例

Policy_ID   Load_DATE   ENDORSEMENT#    SEQUENCE    EXTRACTDATE
25276       8/16/2015       0               1        8/15/2015      
25276       2/13/2016       1               2        2/12/2016
25276       9/24/2016       3               4        9/20/2016
25276       9/24/2016       3               4        9/20/2016
25276       9/24/2016       2               3        9/20/2016

所以首先我们抓住最大加载日期并加入到原始表格然后获取最大代言#然后再加入并获取最大序列然后加入并获取最大提取日期以最终返回到我们的最终记录所以它将是独一无二的。以上是一个例子。

有更简单的方法吗?有人提到row_number()over(partition by),但我认为只返回你想要的行号。我可以通过一次滑动快速获取具有上述所有属性的最多记录。有没有人有更好的想法,因为这些查询需要一段时间才能运行。

由于

2 个答案:

答案 0 :(得分:1)

@Bryant,

首先,@ Backs为你保存了这篇文章。当我第一次看到它时,我想“该死的。如果他不想花时间让他的请求可读,我为什么要打扰”?此外,如果您正在寻找一个编码示例,那么最好创建一些易于使用的测试数据,以便人们更轻松地帮助您。另外,正如@Felix Pamittan建议的那样,你也应该发布你预期的回报。

这是发布易耗品测试数据的一种方法。我还添加了另一个Policy_ID,以便我可以演示如何为整个表而不是一个Policy_ID执行此操作。

--===== If the test table doesn't already exist, drop it to make reruns in SSMS easier.
     -- This is NOT a part of the solution. We're just simulating the original table
     -- using a Temp Table.
     IF OBJECT_ID('tempdb..#TBL_POL','U') IS NOT NULL
   DROP TABLE #TBL_POL
;
--===== Create the test table (technically, a heap because no clustered index)
     -- Total SWAG on the data-types because you didn't provide those, either.
 CREATE TABLE #TBL_POL
        (
         Policy_ID      INT     NOT NULL
        ,Load_DATE      DATE    NOT NULL
        ,ENDORSEMENT#   TINYINT NOT NULL
        ,SEQUENCE       TINYINT NOT NULL
        ,EXTRACTDATE    DATE    NOT NULL
        )
;
--===== Populate the test table
 INSERT INTO #TBL_POL
        (Policy_ID,Load_DATE,ENDORSEMENT#,SEQUENCE,EXTRACTDATE)
 SELECT Policy_ID,Load_DATE,ENDORSEMENT#,SEQUENCE,EXTRACTDATE
   FROM (VALUES
        --===== Original values provided
         (25276,'8/16/2015',0,1,'8/15/2015')  
        ,(25276,'2/13/2016',1,2,'2/12/2016')
        ,(25276,'9/24/2016',3,4,'9/20/2016')
        ,(25276,'9/24/2016',3,4,'9/20/2016')
        ,(25276,'9/24/2016',2,3,'9/20/2016')
        --===== Additional values to demo multiple Policy_IDs with
        ,(12345,'8/16/2015',0,1,'8/15/2015')  
        ,(12345,'9/24/2016',1,5,'2/12/2016')
        ,(12345,'2/13/2016',1,2,'2/12/2016')
        ,(12345,'9/24/2016',3,4,'9/20/2016')
        ,(12345,'9/24/2016',3,4,'9/20/2016')
        ,(12345,'9/24/2016',2,3,'9/20/2016')

        ) v (Policy_ID,Load_DATE,ENDORSEMENT#,SEQUENCE,EXTRACTDATE)
;
--===== Show what's in the test table
 SELECT * 
   FROM #TBL_POL
;

如果您希望一次解决多个Policy_ID的问题,那么以下内容将有效。

--===== Use a partitioned windowing function to find the latest row
     -- for each Policy_ID, ignoring "dupes" in the process.
     -- This assumes that the "sequence" column is king of the hill.
   WITH cteEnumerate AS
        (
         SELECT *
                ,RN = ROW_NUMBER() OVER (PARTITION BY Policy_ID ORDER BY SEQUENCE DESC)
           FROM #TBL_POL
        )
 SELECT Policy_ID,Load_DATE,ENDORSEMENT#,SEQUENCE,EXTRACTDATE
   FROM cteEnumerate
  WHERE RN = 1
;

如果您只是为此寻找一个Policy_ID,@ ZLK建议的“TOP 1”方法将起作用,但也会在上面添加WHERE子句。不确定哪个会更快,但相同的索引将有助于两者。这是带有WHERE子句的解决方案(可以参数化)。

--===== Use a partitioned windowing function to find the latest row
     -- for each Policy_ID, ignoring "dupes" in the process.
     -- This assumes that the "sequence" column is king of the hill.
   WITH cteEnumerate AS
        (
         SELECT *
                ,RN = ROW_NUMBER() OVER (PARTITION BY Policy_ID ORDER BY SEQUENCE DESC)
           FROM #TBL_POL
          WHERE Policy_ID = 25276
        )
 SELECT Policy_ID,Load_DATE,ENDORSEMENT#,SEQUENCE,EXTRACTDATE
   FROM cteEnumerate
  WHERE RN = 1
;

答案 1 :(得分:0)

可能你应该尝试分组SET

抛出另一个样本数据。 我也不确定表现。

提供反馈,但结果和表现

var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
  entry: {
    app: './src/main.ts',
    polyfills: './src/polyfills.ts'
  },
  output: {
    path: path.resolve('dist'),
    filename: '[name].js',
    publicPath: 'assets/'
  },
  resolve: {
    // only discover files that have those extensions
    extensions: ['.ts', '.js', '.json', '.css', '.scss', '.html'],
  },
  module: {
    rules: [{
      test: /\.ts$/,
      exclude: /node_modules/,
      loader: 'awesome-typescript-loader'
    },
    {          
      test: /\.scss$/,
      use: ExtractTextPlugin.extract({
        fallback: 'style-loader',
        use: ['css-loader', 'sass-loader']
      })
    },
    {
      test: /\.html$/,
      loader: 'html-loader'
    },
    {
      test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
      loader: 'file-loader?name=fonts/[name].[hash].[ext]?'
    }
    ]
  },
  plugins: [       
    new ExtractTextPlugin({ filename: 'mystyle.css', disable: false, allChunks: true })
  ]
};