SQL反模式筆記14 關於分組取最大值的問題

2022-02-17 17:07:28 字數 1078 閱讀 6493

目標:要查詢得到每組的max(或者min等其他聚合函式)值,並且得到這個行的其他字段

反模式:引用非分組列

如:select articleid,max(tagid),tagname

from articletag

group by articleid

這一章有點搞,因為這一章的目標用group去實現,根本就是個錯誤(mssql是這樣),語法就不對!

mssql裡用row_number就行了,如果不用group就很麻煩了,比如有乙個people表,裡面有firstname、lastname、age幾個字段,現在想得到每個firstname分組裡年齡最大的人的lastname

用row_number如下:

select firstname,lastname,age

from (

select row_number() over(partition by firstname order by age desc,id asc) as number,*

from people

) x where number=1

用group如下:

select a.firstname,a.lastname,a.age

from people a

join(--根據得到的最大年齡,找其年齡符合的資料,為了避免年齡重複,再對其分組,取最小的id

select min(p1.id) as minid

from people p1

join(--得到每個firstname的最大年齡

select firstname,max(age) as maxage

from people

group by firstname

) p2 on p1.firstname=p2.firstname and p1.age=p2.maxage

group by p1.firstname,p1.age

)b on a.id=b.minid

對比一下就知道,group完全可以被拋棄了。

SQL反模式筆記13 關於NULL值

目標 儲存和使用空值 反模式 將null作為普通的值,或者不適用null 將null作為普通的值 1 在表示式中使用可空列,結果都是null。2 搜尋允許為空的列 只能使用is null is not null,其它方法都沒法搜出null值。3 在查詢引數中使用null,無法將null作為引數傳入。...

SQL反模式筆記18 使用 查詢

目標 減少輸入 反模式 使用 缺點1 傳輸的資料量大。解決方案 明確列出列名 這一章內容太簡單了,好像沒啥可說的。我想起用ibatis的時候遇到的乙個問題 最初的sql都是自動生成的,比如根據id update某個表,輸入引數是這個表對應的乙個entity,包含了這個表幾乎所有的字段。這樣使用的時候...

SQL反模式筆記16 模糊查詢

目標 模糊查詢 反模式 like 缺點 效能太差,無法使用索引,必須全表遍歷。合理使用反模式 資料量小 條件簡單時可以用。解決方案 使用特殊的搜尋引擎而不是sql 1 資料庫擴充套件,各大資料庫都有對全文檢索的解決方案,但是配置複雜。2 使用第三方搜尋引擎,比如lucene.3 實現自己的搜尋引擎 ...