简体   繁体   English

SQL聚合

[英]SQL aggregation

The following is T-SQL executed through a Business Objects package. 以下是通过Business Objects包执行的T-SQL。 My question is, is there a shorter way of completing the following aggregation for a query: 我的问题是,是否有较短的方法来完成查询的以下聚合:

(SELECT tblName.Details
 FROM   tblName
 WHERE  tblName.ID = (SELECT Max(tblName2.ID)
                      FROM   tblName tblName2
                      WHERE  tblMainQuery.id = tblName2.id
                             AND tblName2.StartDate = (SELECT Max(tblName3.StartDate)
                                                       FROM   tblName tblName3
                                                       WHERE  tblMainQuery.id = tblName3.id))) 

tblMainQuery.id is a field which makes it a correlated sub-query. tblMainQuery.id是一个使其成为相关子查询的字段。

So to summarise, I want to implement this whole query as a sub-query, in which I want to retrieve the id of the most recent start date, but as the most recent start date might return more than one record, go down to primary key level and retrieve the highest primary key. 因此,总而言之,我想将整个查询实现为子查询,在其中我要检索最近开始日期的ID,但是由于最近开始日期可能返回多个记录,因此请转到主查询。键级别并检索最高的主键。

I know using a CTE would help but this isn't possible as it must be executed through Business Objects Web Intelligence - this isn't supported. 我知道使用CTE会有所帮助,但这是不可能的,因为必须通过Business Objects Web Intelligence执行-不支持此功能。

I would probably try a ROW_NUMBER . 我可能会尝试ROW_NUMBER Order by startDate to get the max startDate, further order by ID to get the max ID belonging to the max StartDate. 按startDate排序以获取最大startDate,按ID进一步排序以获取属于最大StartDate的最大ID。 Then select only records with ROW_NUMBER = 1. 然后仅选择ROW_NUMBER = 1的记录。

Try this 尝试这个

SELECT *
FROM   tblName A
       JOIN (SELECT TOP 1 Row_number()
                            OVER (
                              ORDER BY startdate, id) row_n,
                          *
             FROM   tblName
             ORDER  BY row_n DESC) B
         ON A.id = b.id 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM