我有一个如下表:
|col1|col2|col3|col4|col5|
|----|----|----|----|----|
|A |1 |x |y |y |
|A |2 |x |x |y |
|B |1 |x |y |x |
我要根据col2中的最大值返回col1中非唯一值的单个记录。
我可以使用内部自连接来完成此操作,例如:
SELECT a.*
FROM table a INNER JOIN (
SELECT col1,
MAX(col2)
FROM table
GROUP BY col1) b
ON b.col1 = a.col1 AND b.col2 = a.col2
哪个会返回:
|col1|col2|col3|col4|col5|
|----|----|----|----|----|
|A |2 |x |x |y |
|B |1 |x |y |x |
但是,这似乎效率很低。有更有效的方法吗?
答案 0 :(得分:1)
我认为您更喜欢直接使用public class Question
{
public int id {get;set;} // or whatever datatype your id is
public int qid {get;set;} // or whatever datatype your qid is
public string qName {get;set;} // chose a datatype that makes sense here
public string qType {get;set;} // chose a datatype that makes sense here
}
/// .....
var questions = dbContext.Sft_Set.Where(s => s.Sft_Set_ID == currentSet)
.Select(s => new Question
{
id = s.Sft_Set_ID,
qid = s.Sft_QuestionID,
qName = s.Sft_Question.Q_Question,
qtype = s.Sft_Question.Q_Type
}).ToList();
Session["questionList"] = questions;
var list = Session["questionList"] as List<Question>;
运算符
in
答案 1 :(得分:1)
使用相关子查询
select * from tablename a
where col2 in (select max(col2) from tablename b where a.col1=b.col1)
答案 2 :(得分:1)
您正在使用Oracle,对于这种简单情况,不需要使用相关子查询或自联接。只需使用解析函数即可。
with s (col1, col2, col3, col4, col5) as (
select 'A', 1, 'x', 'y', 'y' from dual union all
select 'A', 2, 'x', 'x', 'y' from dual union all
select 'B', 1, 'x', 'y', 'x' from dual)
select*
from
(select s.*, max(col2) over (partition by col1) mx
from s
)
where col2 = mx;
C COL2 C C C MX
- ---------- - - - ----------
A 2 x x y 2
B 1 x y x 1
Elapsed: 00:00:00.00
with s (col1, col2, col3, col4, col5) as (
select 'A', 1, 'x', 'y', 'y' from dual union all
select 'A', 2, 'x', 'x', 'y' from dual union all
select 'B', 1, 'x', 'y', 'x' from dual)
select*
from
(select s.*, row_number() over (partition by col1 order by col2 desc) rn
from s
)
where rn = 1;
C COL2 C C C RN
- ---------- - - - ----------
A 2 x x y 1
B 1 x y x 1
Elapsed: 00:00:00.00
with s (col1, col2, col3, col4, col5) as (
select 'A', 1, 'x', 'y', 'y' from dual union all
select 'A', 2, 'x', 'x', 'y' from dual union all
select 'B', 1, 'x', 'y', 'x' from dual)
select
col1,
max(col2) col2,
max(col3) keep (dense_rank last order by col2) col3,
max(col4) keep (dense_rank last order by col2) col4,
max(col5) keep (dense_rank last order by col2) col5
from s
group by col1;
C COL2 C C C
- ---------- - - -
A 2 x x y
B 1 x y x
Elapsed: 00:00:00.01