我如何才能实现某些字段的区别,并且返回结果集包括所有列?
下面是sql查询:
SELECT DISTINCT FIELD1,FIELD2,FIELD3,FIELD4,FIELD5
FROM T1
RESULT COUNT - 5000
Observation - it is distinct for all five fields as DISTINCT APPLIED ON WHOLE RECORD.
BUt, FIELD1, FIELD2,FIELD43 are just duplicated and vary only FIELD 4, AND field5
另一个sql查询(刚跳过最后两列)。
SELECT DISTINCT FIELD1,FIELD2,FIELD3 --SKIPPED FIELD4,FIELD5
FROM T1
RESULT COUNT - 3000
OBVESERVATION - it shows only distinct record for all three field.
问题:我只需要三个字段的不同记录(FIELD1,FIELD2,FIELD3),它应该包括 - FIELD4,FIELD5
如何实现。
谢谢
答案 0 :(得分:2)
您希望为FIELD4和FIELD5返回什么,具有相同FIELD1-3的任何行的数据?
select *
from
(
SELECT FIELD1,FIELD2,FIELD3,FIELD4,FIELD5,
ROW_NUMBER()
OVER (PARTITION BY FIELD1,FIELD2,FIELD3
ORDER BY FIELD4) as rn
FROM T1
) as dt
where rn = 1;
或者只是来自任何一行的任何数据?
SELECT FIELD1,FIELD2,FIELD3,MIN(FIELD4),MIN(FIELD5)
FROM T1
GROUP BY FIELD1,FIELD2,FIELD3
但是这可能会从两个不同的行返回MIN,因此实际上没有行。