簡體   English   中英

SQL 查詢表中相同值的個數,如果計數大於1,則取第一個值

[英]SQL query for counting the number of same values in a table and fetching the first value if the count is greater than 1

有一個表如

+-----+-------+
| id  | status|
+-----+-------+
| 01  | open  |
| 02  | close |
| 03  | close |
| 04  | close |
| 05  | open  |
| 06  | open  |
| 07  | open  |
| 08  | close |
| 09  | open  |
| 10  | close |
+-----+-------+

我想要打開狀態記錄的數量,如果記錄數大於 1,我想獲取第一個打開狀態記錄 ID。

為此,我一直在嘗試這樣做

SELECT status, count(*) as count from table_name group by status='open' order by status desc limit 1
if(@count>0)
select * from table_name where status like 'open' union select * from table_name limit 1

這似乎不起作用(如果這是一個錯誤,請原諒我)。

如果只有打開狀態記錄的數量大於 1,我最后想要第一個打開狀態記錄的 ID。

你可以使用這樣的查詢:

SELECT STATUS, count(*) AS count, MIN(id) AS FirstID
FROM TABLE_NAME
WHERE STATUS = 'open'
GROUP BY STATUS
HAVING count(*) > 1;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM