SQL query corresponding to the maximum value of a category table field

SQL query corresponding to the maximum value of a category table field


A, SQL queries, a category table corresponding to the field values of the maximum ( operation on a table ):

Question: According to the teacher id query checkOutAutoID a record of the largest in the balance?

explore:

1.group by method:

First lookup table corresponding to the same teacherID checkOutAutoID maxima:

select MAX(checkOutAutoID) from T_CheckOut group by teacherID order by teacherID

The maximum value is then isolated (assuming that the isolated 3), the corresponding isolated remainCash:

SELECT remainCash FROM T_CheckOut WHERE checkOutAutoID=3


Merge SQL:

SELECT remainCash FROM T_CheckOut WHERE checkOutAutoID=(select MAX(checkOutAutoID) from T_CheckOut group by teacherID order by teacherID)


The results given:


Solution:

Join top 1 in the sub-query can be:

SELECT top 1 remainCash FROM T_CheckOut WHERE checkOutAutoID=(select top 1 MAX(checkOutAutoID) from T_CheckOut group by teacherID order by teacherID)

Two data library, run time 0.035s.


2. Nesting:

select remainCash,teacherID,checkOutAutoID from T_CheckOut as a   
    where  checkOutAutoID=(select max(b.checkOutAutoID)  
                      from T_CheckOut as b  
                      where a.teacherID = b.teacherID  
                      )

Curry two data, the running time 0.146s, the above method is relatively efficient is low, over 5 times.


That question is, our checkOutAutoID is unique, if we change the idea, assume checkOutAutoID is not unique, we might find out the checkOutAutoID same record had a lot of pieces, but as long as one of us how to do it? Just do a little modification OK:

select * from
(select remainCash,teacherID,checkOutAutoID from T_CheckOut as a   
    where  checkOutAutoID=(select max(b.checkOutAutoID)  
                      from T_CheckOut as b  
                      where a.teacherID = b.teacherID  
                      )
)as a
group by checkOutAutoID


二、根据卡表中的卡号,插入学生表一条记录(卡表与学生表存在外键关联):

insert into T_Student(cardAutoID,stuID,stuName,sex)select cardAutoID,@stuID,@stuName,@sexfrom T_Card where cardID=@cardID


总结:

group by方法相对嵌套来说,查询效率高,语句简单,不易出错,所以还是建议使用第一种方法。


感谢您的阅读!





发布了253 篇原创文章 · 获赞 76 · 访问量 29万+

Guess you like

Origin blog.csdn.net/hongwei15732623364/article/details/54668512