各位好:
我剛剛開始接觸資料庫,前幾天面試的時候碰到這樣一個問題:一張表FIRST,表結構和資料如下圖:

(當時考題中沒有ID這一欄,是我不知道怎么定位是第幾行資料而自己加的)
題目要求是:將記錄按照type的值分類,將每類中CODE的ASCⅡ的值第二大的記錄查詢出來。提示是表關聯和const指令。
我當時想了很久,使用
select const(*),type from first group by type;能得到每類的記錄數,通過運算式也能定位到第二大的記錄應該是哪行。
我的問題是:
1。如何查詢一張表具體到第幾行的記錄
2。用什么指令能將我查詢出的結果作為臨時表和原表關聯起來。
3。原題中CODE的值是數字,比較ASCⅡ碼比較簡單,如果還包含字母,這個比較怎么在SQL陳述句中實作。
希望能得到幫助,謝謝各位。
uj5u.com熱心網友回復:
select * from(select a.*,row_num()over(partition by type order by ascii(code) as rn from t1 a) b where b.rn2
uj5u.com熱心網友回復:
uj5u.com熱心網友回復:
SELECT Max(a.code),a.type FROM first AS a Left Join first AS b ON a.type = b.type AND a.code< b.code WHERE b.code IS NOT NULL GROUP BY a.typeuj5u.com熱心網友回復:
# 查找每一條記錄中有相同type的所有記錄,統計code大于本條記錄的數量,如果只有一條記錄的code大于本條記錄,則本條記錄的code
# 就是第二大的,并用 exists 將本條記錄篩選出來。
select *
from first as a
where exists(select count(*) as num
from first
where a.type = type and a.code < code
having num = 1);
uj5u.com熱心網友回復:
先查詢出code acsii的最大值 ,再找出所有比這個最大值小的所有code值后進行分組 再取這個組里的最大值 就是第二大的了select max(code) as code,type from first
where ascii(code) <
(select max(ascii(code)) from bb)
group by type
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/81799.html
標籤:MySQL
