除了ID和时间戳之外,所有字段都相同时获取第一条记录?

时间:2016-06-09 15:58:38

标签: sql intersystems-cache

这是我当前的查询:

SELECT  TOP 6 *
FROM    HS_IHE_ATNA_Repository.Aggregation
WHERE   EventType = 'Retrieve Document Set'

它返回与此类似的数据:

ID     TimeStamp    tid    Fruit      Color       User     EventType
1      12:30:31     001    Apple      Red         Paul     Retrieve Document Set
2      12:30:32     001    Apple      Red         Paul     Retrieve Document Set
3      12:31:03     002    Orange     Orange      Steve    Retrieve Document Set
4      12:31:04     002    Orange     Orange      Steve    Retrieve Document Set
5      12:34:12     003    Banana     Yellow      Paul     Retrieve Document Set
6      12:34:13     003    Banana     Yellow      Paul     Retrieve Document Set

我希望我的查询只返回记录1,3和5.基本上,所有内容都有一个独特的tid。我怎么能这样做?

2 个答案:

答案 0 :(得分:5)

尝试:

SELECT  distinct(*)
FROM    HS_IHE_ATNA_Repository.Aggregation a
WHERE   EventType = 'Retrieve Document Set'
AND     TimeStamp = (select min(b.TimeStamp) from from HS_IHE_ATNA_Repository.Aggregation b 
                      WHERE b.tid = a.tid)
ORDER BY ID asc

答案 1 :(得分:1)

您需要创造性地使用GROUP BY:

SELECT  TOP 6 MAX(TimeStamp), *
FROM    HS_IHE_ATNA_Repository.Aggregation
WHERE   EventType = 'Retrieve Document Set'
GROUP BY tid||Fruit||Color||User

这会将具有相同tid的所有行分组,即Fruit,Color,User。或者你可以连接concat函数: GROUP BY {fn CONCAT(tid,{fn CONCAT(Fruit,{fn CONCAT(Color,User)})})}