SQL查询为一列中值为0的行和另一列中的唯一ID选择记录

时间:2014-04-25 07:11:29

标签: mysql sql sql-server

ID       amount account number(varchar)
5105     0.70   23423423
5105     0.0    null
5105     0.0    null
5104     0.0    null
5104     0.0    null
5104     0.0    null
5106     0.0    32132111
5106     0.0    null

我想获得所有金额值为0.0且帐号为空的非常ID。基本上从这个表我想要的结果为5104.任何人都可以帮助我,我是SQL的新手。

4 个答案:

答案 0 :(得分:1)

Select DISTINCT ID FROM TableName 
GROUP BY ID
HAVING min(amount)=0.0 and max(amount)=0.0

答案 1 :(得分:0)

Select DISTINCT ID FROM TableName 
    GROUP BY ID
      HAVING SUM(amount)=0.0

更新另一个条件(另一个列是varchar。它应该为null)

  Select DISTINCT ID FROM TableName 
      WHERE AnotherColumn IS NULL
        GROUP BY ID
          HAVING SUM(amount)=0.0

SQL小提琴:http://sqlfiddle.com/#!2/145504/3

答案 2 :(得分:0)

这有效:

SELECT ID, MAX(amount) FROM table_name GROUP BY ID HAVING MAX(amount)=0

这里是fiddle

答案 3 :(得分:0)

您可以使用

SELECT id,
       MIN(amount) AS minumum,
       MAX(amount) AS maximum
FROM your_table
GROUP BY id HAVING minimum = 0.0
AND maximum = 0.0
在我看来,一个简单的总和不会起作用,因为你可以得到-1和1中的一个,总和为0.

由于你没有写过,如果你有负值,那么检查最低值也是必要的。

增加新限制:

SELECT id,
       MIN(amount) AS min_value,
       MAX(amount) AS max_value,
       MAX(account) AS max_account
FROM your_table
GROUP BY id 
HAVING min_value = 0.0
AND max_value = 0.0
AND max_account IS null