根据ID组合最新数据

时间:2017-02-27 14:22:37

标签: sql-server tsql

我在表格中有这样的数据,我正在尝试获取如下数据。我尝试使用coalese,但在获取最新数据方面存在问题。

Key             Hazards             DateTime
170021          Safety              2016-01-25 
170021          Concerns            2016-01-25
170021          Abuse               2016-01-25
252098          Financial           2016-10-28 
250606          Environmental       2016-10-26 
359287          food,utilities      2016-08-08 
409153          climate control     2016-06-24 
671881          None                2016-05-24 

Answer: Safety,Concerns,Abuse

结果应如上所述。我想要做的是根据DateTime的最新值获取密钥,如果该Key可用的多个记录将它们连接成一个字符串并返回。如果只有单个记录才能获得该记录。

3 个答案:

答案 0 :(得分:1)

SQL Server 2016,您可以使用STRING_AGG

index.hbs

答案 1 :(得分:1)

这对你有帮助吗?

;WITH testtable([Key],Hazards,[DateTime])AS(
    SELECT '170021','Safety',CONVERT(DATE,'2016-01-25') UNION all
    SELECT '170021','Concerns','2016-01-25' UNION all
    SELECT '170021','Abuse','2016-01-25' UNION ALL
    SELECT '170021','Abuse','2016-01-24' UNION ALL
    SELECT '170021','Abuse2','2016-01-23' UNION ALL
    SELECT '170021','Abuse3','2016-01-22' UNION ALL
    SELECT '170021','Abuse4','2016-01-21' UNION all
    SELECT '252098','Financial','2016-10-28' UNION all
    SELECT '250606','Environmental','2016-10-26' UNION all
    SELECT '359287','food,utilities','2016-08-08' UNION all
    SELECT '409153','climate control','2016-06-24' UNION all
    SELECT '671881','None','2016-05-24'
)
SELECT DISTINCT t.[Key],t.DateTime,STUFF(c.Hazards,1,1,'') AS Hazards FROM (
    SELECT *,RANK()OVER(PARTITION BY [Key] ORDER BY DateTime DESC) AS rn FROM testtable
) AS t 
CROSS APPLY(SELECT ','+tt.Hazards FROM testtable AS tt WHERE tt.[Key]=t.[Key] AND DATEDIFF(d,tt.DateTime,t.DateTime)=0 FOR XML PATH('')) AS c(Hazards)
WHERE rn=1
Key    DateTime   Hazards
------ ---------- --------------
170021 2016-01-25 Safety,Concerns,Abuse
250606 2016-10-26 Environmental
252098 2016-10-28 Financial
359287 2016-08-08 food,utilities
409153 2016-06-24 climate control
671881 2016-05-24 None

答案 2 :(得分:0)

在存储过程中使用while循环

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="title" style="margin-top:15px;margin-left:15px;">
  <img class="click" src="@Url.Content(" ~/Images/plus_plus.png ")"  />
  <span>
</span>

  <a class="click2" style="margin-left:10px;">
    <img src='@Url.Content("~/Images/arrow.png")' />
  </a>

</div>
<hr>
<hr>
<div class="title2"></div>