SQL中的三種去重方法小結(jié)
在使用SQL提數(shù)的時候,常會遇到表內(nèi)有重復值的時候,比如我們想得到 uv (獨立訪客),就需要做去重。
在 MySQL 中通常是使用 distinct 或 group by子句,但在支持窗口函數(shù)的 sql(如Hive SQL、Oracle等等) 中還可以使用 row_number 窗口函數(shù)進行去重。
舉個栗子,現(xiàn)有這樣一張表 task:
task_id | order_id | start_time |
---|---|---|
1 | 123 | 2020-01-05 |
1 | 213 | 2020-01-06 |
1 | 321 | 2020-01-07 |
2 | 456 | 2020-01-06 |
2 | 465 | 2020-01-07 |
3 | 798 | 2020-01-06 |
備注:
- task_id: 任務id;
- order_id: 訂單id;
- start_time: 開始時間
注意:一個任務對應多條訂單
我們需要求出任務的總數(shù)量,因為 task_id 并非唯一的,所以需要去重:
distinct
-- 列出 task_id 的所有唯一值(去重后的記錄) -- select distinct task_id -- from Task; -- 任務總數(shù) select count(distinct task_id) task_num from Task;
distinct 通常效率較低。它不適合用來展示去重后具體的值,一般與 count 配合用來計算條數(shù)。
distinct 使用中,放在 select 后邊,對后面所有的字段的值統(tǒng)一進行去重。比如distinct后面有兩個字段,那么 1,1 和 1,2 這兩條記錄不是重復值 。
group by
-- 列出 task_id 的所有唯一值(去重后的記錄,null也是值) -- select task_id -- from Task -- group by task_id; -- 任務總數(shù) select count(task_id) task_num from (select task_id from Task group by task_id) tmp;
row_number
row_number 是窗口函數(shù),語法如下:
row_number() over (partition by <用于分組的字段名> order by <用于組內(nèi)排序的字段名>)
其中 partition by 部分可省略。
-- 在支持窗口函數(shù)的 sql 中使用 select count(case when rn=1 then task_id else null end) task_num from (select task_id , row_number() over (partition by task_id order by start_time) rn from Task) tmp;
此外,再借助一個表 test 來理理 distinct 和 group by 在去重中的使用:
user_id | user_type |
---|---|
1 | 1 |
1 | 2 |
2 | 1 |
-- 下方的分號;用來分隔行 select distinct user_id from Test; -- 返回 1; 2 select distinct user_id, user_type from Test; -- 返回1, 1; 1, 2; 2, 1 select user_id from Test group by user_id; -- 返回1; 2 select user_id, user_type from Test group by user_id, user_type; -- 返回1, 1; 1, 2; 2, 1 select user_id, user_type from Test group by user_id; -- Hive、Oracle等會報錯,mysql可以這樣寫。 -- 返回1, 1 或 1, 2 ; 2, 1(共兩行)。只會對group by后面的字段去重,就是說最后返回的記錄數(shù)等于上一段sql的記錄數(shù),即2條 -- 沒有放在group by 后面但是在select中放了的字段,只會返回一條記錄(好像通常是第一條,應該是沒有規(guī)律的)
到此這篇關于SQL中的三種去重方法小結(jié)的文章就介紹到這了,更多相關SQL 去重內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持本站!
版權聲明:本站文章來源標注為YINGSOO的內(nèi)容版權均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務器上建立鏡像,否則將依法追究法律責任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學習參考,不代表本站立場,如有內(nèi)容涉嫌侵權,請聯(lián)系alex-e#qq.com處理。