根据两列中的值选择行

时间:2015-08-20 16:01:28

标签: sql sql-server select

这是我的表

 ID  prod   Num 
-------------------
| 1 | A  |  4
| 1 | B  |  3
| 1 | K  |  2
| 2 | A  |  4
| 2 | B  |  4
| 2 | C  |  2
| 3 | A  |  1
| 3 | K  |  4

首先,我需要Num = 4的所有行,并且对于相同的ID存在Prod = K

结果1应为

ID  prod   num 
-------------------
| 1 | A  |  4
| 1 | B  |  3
| 1 | K  |  2
| 3 | A  |  1
| 3 | K  |  4

我还需要另一个只有行的结果:Num = 4或Prod = K.  从第一次查询

结果2:

ID  prod   num 
-------------------
| 1 | A  |  4
| 1 | K  |  2
| 3 | A  |  1
| 3 | K  |  4

谢谢你们。

3 个答案:

答案 0 :(得分:2)

结果1:

select t.id,t.prod,t.num
from mytable t 
join
(select distinct id
from mytable x
where num = 4
and exists(select 1 from mytable where id = x.id and prod = 'K') ) x
on t.id = x.id

结果2:

with res1 as (select t.id,t.prod,t.num
from mytable t 
join
(select distinct id
from mytable x
where num = 4
and exists(select 1 from mytable where id = x.id and prod = 'K') ) x
on t.id = x.id
)
select * from res1 where num = 4 or prod = 'K'

你可以试试这个。

Fiddle

答案 1 :(得分:0)

您可以使用以下查询:

SELECT ID
FROM mytable
WHERE Num = 4 OR Prod = 'K'
GROUP BY ID
HAVING COUNT(CASE WHEN Prod = 'K' THEN 1 END) <> 0 
       AND COUNT(CASE WHEN Num = 4 THEN 1 END) <> 0

获取符合您的搜索要求的ID值,即(1), (3)

在上面应用IN运算符可以得到所需的结果集1:

SELECT ID, prod, Num
FROM mytable
WHERE ID IN (
   SELECT ID
   FROM mytable
   WHERE Num = 4 OR Prod = 'K'
   GROUP BY ID
   HAVING COUNT(CASE WHEN Prod = 'K' THEN 1 END) <> 0 
          AND COUNT(CASE WHEN Num = 4 THEN 1 END) <> 0 )

要获取结果集2,只需将Num=4 OR Prod='K'谓词添加到上述查询的WHERE子句中。

Demo here

答案 2 :(得分:0)

对于第一个查询:

SELECT t.* FROM table t
LEFT OUTER JOIN table t2 ON t2.id = t.id AND t2.num=4
LEFT OUTER JOIN table t3 ON t3.id =t.id AND t3.prod='K'
WHERE t2.id IS NOT NULL AND t3.id IS NOT NULL
ORDER BY t.id,t.prod

第二个问题:

SELECT t.* FROM table t
LEFT OUTER JOIN table t2 ON t2.id = t.id AND t2.num=4
LEFT OUTER JOIN table t3 ON t3.id =t.id AND t3.prod='K'
WHERE t2.id IS NOT NULL AND t3.id IS NOT NULL
AND (t.num=4 OR t.prod='K')
ORDER BY t.id,t.prod