我对SQL Group By Statement
有疑问首先这是我的表 - > TEMP_DATA
id | a_id | date_time | length | <br>
1074 | 3 | 2016-12-07 09:13:13.490 | 1.036013 | <br>
1075 | 1 | 2016-12-07 09:13:13.690 | 1.699601 | <br>
1076 | 0 | 2016-12-07 09:13:13.867 | 2.110443 | <br>
1077 | 3 | 2016-12-07 09:13:14.490 | 1.027660 | <br>
1078 | 1 | 2016-12-07 09:13:14.690 | 1.742645 | <br>
1079 | 0 | 2016-12-07 09:13:14.867 | 2.121963 | <br>
1080 | 2 | 2016-12-07 09:13:18.390 | 4.008482 | <br>
我尝试通过id asc选择3个不同的a_id顺序的id,a_id,date_time,length 所以我用这个
SELECT DISTINCT
a_id,
Min(id) id,
Min(Last_Data.lenght) lenght,
(Select date_time from temp_data
where temp_data.id = Min(Last_Data.id)) last_time
FROM (
SELECT *
FROM temp_data
where id >= 1074 and id <= 1080
) Last_Data
GROUP BY a_id
order by id asc
结果是
id | a_id | last_time | length | <br>
1074 | 3 | 2016-12-07 09:13:13.490 | 1.013928 | <br>
1075 | 1 | 2016-12-07 09:13:13.690 | 1.699601 | <br>
1076 | 0 | 2016-12-07 09:13:13.867 | 2.110443 | <br>
我的ID长度值错误。我该如何解决这个问题?
P.S。 :首先我在这张表中得到3个不同的a_id。然后我使用select top 3 *语句。因为两个相同的a_id可以连续出现。例如
id | a_id | date_time | length | <br>
1074 | 1 | 2016-12-07 09:13:13.490 | 1.013928 | <br>
1075 | 1 | 2016-12-07 09:13:13.690 | 1.699601 | <br>
答案 0 :(得分:0)
您可以将<link data-require="bootstrap@3.3.6" data-semver="3.3.6" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script data-require="angular.js@1.5.8" data-semver="1.5.8" src="https://code.angularjs.org/1.5.8/angular.js"></script>
<script data-require="angular-filter@0.5.7" data-semver="0.5.7" src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.7/angular-filter.js"></script>
<div ng-app="app" ng-controller="mainCtrl">
<div ng-repeat="json in myJson|chunkBy:4" class="row">
<div class="item col-md-3 col-sm-4 col-xs-6" ng-repeat="item in json">
<strong>{{item.name}}</strong><br>
{{item.desc}}
</div>
</div>
</div>
分析函数与first_value
子句一起使用:
over
答案 1 :(得分:0)
;with cteData as
(
SELECT
t.a_id, t.id, t.date_time, t.lenght,
row_number() over(partition by t.a_id order by t.date_time desc) rn
FROM temp_data t
where id >= 1074 and id <= 1080
)
select
d.a_id, d.id, d.date_time as last_date_time, t.length
from cteData d
where d.rn = 1