Get Last Row of Different id then display data that is greater than zero

只愿长相守 提交于 2019-12-25 12:48:16

问题


This is my table...

+----+--------+
| id | amount |
+----+--------+
| 1  | 100    |
| 1  | 50     |
| 1  | 0      |
| 2  | 500    |
| 2  | 100    |
| 3  | 300    |
| 3  | -2     |
| 4  | 400    |
| 4  | 200    |
+----+--------+

I would like to choose from it each value of id that does not have a nonpositive (i.e. negative or 0) value associated with it, and the smallest amount associated with that id.

If I use this code...

SELECT DISTINCT id, amount 
FROM table t 
WHERE amount = (SELECT MIN(amount) FROM table WHERE id= t.id)

... then these results show...

+----+--------+
| id | amount |
+----+--------+
| 1  | 0      |
| 2  | 100    |
| 3  | -2     |
| 4  | 200    |
+----+--------+

But what I want the statement to return is...

+----+--------+
| id | amount |
+----+--------+
| 2  | 100    |
| 4  | 200    |
+----+--------+

回答1:


Just add amount>0 in your query. You missed out that condition in your query. That should do it.

SELECT DISTINCT id, amount FROM table t 
WHERE amount = (SELECT MIN(amount) FROM table WHERE id= t.id)
and amount>0;



回答2:


If you want to display id, where min(amount) > 0, the use this.

SELECT id, min(amount) as amount
FROM table t 
group by id
having min(amount) > 0;



回答3:


Please try the following...

SELECT id,
       MIN( amount )
FROM table
WHERE amount > 0
GROUP BY id
ORDER BY id;

This statement starts by selecting all records WHERE amount is larger than 0.

The records from the resulting dataset are then grouped by each surviving value of id and the smallest value of amount is chosen for that GROUP / id.

The resulting pairs of values are then sorted by ORDER id and returned to the user.

If you have any questions or comments, then please feel free to post a Comment accordingly.



来源:https://stackoverflow.com/questions/43861893/get-last-row-of-different-id-then-display-data-that-is-greater-than-zero

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!