开发者

distinct key word only for one column

I'm using postgresql as my database, I'm stuck with getting desired results 开发者_C百科with a query,

what I have in my table is something like following,

nid    date_start    date_end

1      20            25
1      20            25
2      23            26
2      23            26 

what I want is following

nid    date_start    date_end

1      20            25  
2      23            26

for that I used SELECT DISTINCT nid,date_start,date_end from table_1 but this result duplicate entries, how can I get distinct nid s with corresponding date_start and date_end? can anyone help me with this?

Thanks a lot!


Based on your sample data and sample output, your query should work fine. I'll assume your sample input/output is not accurate.

If you want to get distinct values of a certain column, along with values from other corresponding columns, then you need to determine WHICH value from the corresponding columns to display (your question and query would otherwise not make sense). For this you need to use aggregates and group by. For example:

SELECT
   nid,
   MAX(date_start),
   MAX(date_end) 
FROM
   table_1
GROUP BY
   nid


That query should work unless you are selecting more columns. Or maybe you are getting the same nid with a different start and/or end date


Try distinct on:

select distinct on (col1) col1, col2 from table;


DISTINCT can't result in duplicate entries - that's what it does... removed duplicates.

Is your posted data is incorrect? Exactly what are your data and output?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜