特定组按SQL Server中的最新日期

时间:2017-11-15 10:15:08

标签: sql sql-server

我想对以下数据集运行SQL查询

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:camel="http://camel.apache.org/schema/spring"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:cxf="http://camel.apache.org/schema/cxf"
   xsi:schemaLocation="
   http://camel.apache.org/schema/spring 
    http://camel.apache.org/schema/spring/camel-spring.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/cxf
http://camel.apache.org/schema/cxf/camel-cxf.xsd">

<cxf:cxfEndpoint id="customerEndpoint"
                 address="http://localhost:8080/TestService/"
                 serviceClass="my.package.TestService"
                 wsdlURL="WEB-INF/CustomerService.wsdl"/>

<bean id="logBean" class="my.package.LogBean"/>

<camel:camelContext xmlns="http://camel.apache.org/schema/spring">
    <route>
        <from uri="cxf:bean:customerEndpoint" /> 
        <to uri="bean:logBean" />
    </route>
</camel:camelContext>

我想得到以下结果

date       creation_date    value
------------------------------------
2018-01-01 2017-05-05       1
2018-01-02 2017-05-05       0
2018-01-03 2017-05-05       1
2018-01-04 2017-05-05       0
2018-01-05 2017-05-05       1
2018-01-06 2017-05-05       1
2018-01-02 2017-05-11       5

基本上我想获取所有日期,按日期对其进行分组并获取最新创建日期并获取该创建日期的值。

我试过

2018-01-01 2017-05-05       1
2018-01-02 2017-05-11       5
2018-01-03 2017-05-05       1
2018-01-04 2017-05-05       0
2018-01-05 2017-05-05       1
2018-01-06 2017-05-05       1

但是没有这样做。

2 个答案:

答案 0 :(得分:2)

我认为你可以使用这样的查询:

select *
from (
    select *
        , row_number() over (partition by date, blocked order by creation_date desc) seq
     from datasource) t
where t.seq = 1;

SQL Server Fiddle Demo

答案 1 :(得分:1)

尝试使用子查询并加入它

SELECT d.*
FROM datasource d
JOIN
  (
    SELECT [date],MAX(Creation_date) LastCreationDate
    FROM datasource
    GROUP BY [date]
  ) l
ON d.[date]=l.[date] AND d.Creation_date=l.LastCreationDate

如果所有Creation_date

[date],则第二种变体
SELECT *
FROM datasource
WHERE Creation_date=(SELECT MAX(Creation_date) FROM datasource)