![](/img/trans.png)
[英]Compare the values within the same column against other columns in SQL Server
[英]Compare one value with other values within a group SQL Server
我有下表,其中列名是Item
, Point
和IsCorrect
。
Item | Point | IsCorrect | Not actual column, just logic
-----+-------+-----------+--------------------
1 | 5 | 0 | 5 >= 6
1 | 8 | 0 | 8 >= 6
1 | 9 | 0 | 9 >= 6
1 | 6 | 1 | 6 >= 6
2 | 8 | 0 | 8 >= 7
2 | 7 | 1 | 7 >= 7
2 | 8 | 0 | 8 >= 7
2 | 9 | 0 | 9 >= 7
3 | 2 | 0 | 2 >= 9
3 | 5 | 0 | 5 >= 9
3 | 8 | 0 | 8 >= 9
3 | 9 | 1 | 9 >= 9
我想先按項目分組,得到一個 IsCorrect = 1 的點值,將其與其他點值進行比較(如第 4 列所示)。 如果組內的所有條件都匹配,則 select 該項目。 我期待以下結果。
Item | Point | IsCorrect
-----+-------+----------
2 | 8 | 0
2 | 7 | 1
2 | 8 | 0
2 | 9 | 0
我想使用分區,而不是分組。 非常感謝你的幫助。
想到 Window 功能:
select t.*
from (select t.*,
max(case when iscorrect = 1 then point end) over (partition by item) as point_correct,
min(point) over (partition by item) as min_point
from t
) t
where min_point >= point_correct;
您也可以使用子查詢來執行此操作。 像這樣的東西:
select t.*
from t
where t.item in (select t2.item
from t t2
group by t2.item
having min(t2.point) >= min(case when t2.iscorrect then point end)
);
也就是說,對於每個項目,將最小point
與“正確” point
進行比較。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.