简体   繁体   English

SQL查询仅根据列的值返回某些行

[英]SQL Query to only return certain rows depending on value of column

I have a table that is similar to: 我有一个类似于以下表格:

cycle | id    | name
------|-------|------
0     | 0012  | bob
s     | 0012  | bob
1     | 0012  | bob
0     | 6208  | sally
1     | 6208  | sally
0     | 3276  | jane
s     | 3276  | jane
1     | 3276  | jane
0     | 8736  | harry
s     | 8736  | harry

I need a query that will result in: 我需要一个查询,将导致:

cycle | id    | name
------|-------|------
s     | 0012  | bob
0     | 6208  | sally
s     | 3276  | jane
s     | 8736  | harry

So only return rows that have a 'cycle' value of "s", unless there is no value of "s" for a particular 'id' in which case it should return the row with the 'cycle' value of "0". 因此,仅返回“循环”值为“ s”的行,除非特定“ id”没有“ s”的值,在这种情况下,它应返回“循环”值为“ 0”的行。

SELCET cycle, id, name from tbl1 as t1 where cycle='s' or 
(cycle=0 and (select count(cycle) from tbl1 as t2 where t2.id = t1.id and t2.cycle='s') <= 0)
group by t1.cycle,t1.id;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM