开发者

How to select distinct-columns along with one nondistinct-column in DB2?

开发者 https://www.devze.com 2023-03-24 02:42 出处:网络
I need to perform distinct select on few columns out of which, one column is non-distinct. Can I specify which columns make up the distinct group in my SQL statement.

I need to perform distinct select on few columns out of which, one column is non-distinct. Can I specify which columns make up the distinct group in my SQL statement.

Currently I am doing this.

Select distinct a,b,c,d from TABLE_1 inner join TABLE_2 on TABLE_1.a = TABLE_2.a where TABLE_2.d IS NOT NULL;

The problem I have is I am getting 2 rows for the above SQL because column D holds different values. How can I form a distinct group of columns (a,b&c) ignoring column d, bu开发者_JAVA技巧t have column d in my select clause as well?

FYI: I am using DB2

Thanks Sandeep


SELECT a,b,c,MAX(d) 
FROM table_1 
INNER JOIN table_2 ON table_1.a = table_2.a 
GROUP BY a,b,c


Well, your question, even with refinements, is still pretty general. So, you get a general answer.

Without knowing more about your table structure or your desired results, it may be impossible to give a meaningful answer, but here goes:

SELECT a, b, c, d
FROM table_1 as t1
JOIN table_2 as t2
ON t2.a = t1.a
AND t2.[some_timestamp_column] = (SELECT MAX(t3.[some_timestamp_column])
                                  FROM table_2 as t3
                                  WHERE t3.a = t2.a)

This assumes that table_1 is populated with single rows to retrieve, and that the one-to-many relationship between table_1 and table_2 is created because of different values of d, populated at unique [some_timestamp_column] times. If this is the case, it will get the most-recent table_2 record that matches to table_1.

0

精彩评论

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

关注公众号