简体   繁体   English

当其中一列和另一列大于

[英]SQL select distinct when one column in and another column greater than

Consider the following dataset: 考虑以下数据集:

+---------------------+
| ID | NAME  | VALUE  |
+---------------------+
| 1  | a     | 0.2    |
| 1  | b     | 8      |  
| 1  | c     | 3.5    |
| 1  | d     | 2.2    |
| 2  | b     | 4      |
| 2  | c     | 0.5    |
| 2  | d     | 6      |
| 3  | a     | 2      |
| 3  | b     | 4      |
| 3  | c     | 3.6    |
| 3  | d     | 0.2    |
+---------------------+

I'm tying to develop a sql select statement that returns the top or distinct ID where NAME 'a' and 'b' both exist and both of the corresponding VALUE's are >= '1'. 我打算开发一条sql select语句,该语句返回名称“ a”和“ b”都存在且两个对应的VALUE均大于等于“ 1”的顶部或不同ID。 Thus, the desired output would be: 因此,所需的输出将是:

+---------------------+
| ID | NAME  | VALUE  |
+---------------------+
| 3  | a     | 2      |
+----+-------+--------+

Appreciate any assistance anyone can provide. 感谢任何人都可以提供的帮助。

You can try to use MIN window function and some condition to make it. 您可以尝试使用MIN窗口功能和某些条件来实现它。

SELECT * FROM (
    SELECT *,
    MIN(CASE WHEN NAME = 'a' THEN [value] end) OVER(PARTITION BY ID) aVal,
    MIN(CASE WHEN NAME = 'b' THEN [value] end) OVER(PARTITION BY ID) bVal
    FROM T
) t1
WHERE aVal >1 and bVal >1 and aVal = [Value]

sqlfiddle sqlfiddle

This seems like a group by and having query: 这似乎是一个group by ,并having查询:

select id
from t
where name in ('a', 'b')
having count(*) = 2 and
       min(value) >= 1;

No subqueries or join s are necessary. 不需要子查询或join

The where clause filters the data to only look at the "a" and "b" records. where子句过滤数据以仅查看“ a”和“ b”记录。 The count(*) = 2 checks that both exist. count(*) = 2检查两者是否存在。 If you can have duplicates, then use count(distinct name) = 2 . 如果可以重复,则使用count(distinct name) = 2

Then, you want the minimum value to be 1, so that is the final condition. 然后,您希望最小值为1,这就是最终条件。

I am not sure why your desired results have the "a" row, but if you really want it, you can change the select to: 我不确定为什么您想要的结果带有“ a”行,但是如果您确实想要它,可以将select更改为:

select id, 'a' as name,
       max(case when name = 'a' then value end) as value

you can use in and sub-query 您可以使用in和子查询

select top 1 * from t
where t.id in
(
select id from t
where name in ('a','b')
group by id 
having sum(case when value>1 then 1 else 0)>=2
)
order by id 

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

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