MySQL分組查詢 elt,interval的使用 分數段分佈統計

首先介紹一下這兩個函數

1.elt()

ELT(N,str1,str2,str3,…)

如果N= 1,返回str1,如果N= 2,返回str2,等等。如果N小於1或大於參數個數,返回NULL。ELT()是FIELD()反運算。

mysql> select ELT(1, ‘ej’, ‘Heja’, ‘hej’, ‘foo’);

-> ‘ej’

mysql> select ELT(4, ‘ej’, ‘Heja’, ‘hej’, ‘foo’);

-> ‘foo’

2.interval()

Return the index of the argument that is less than the first argument(小於後面的某個參數,就返回這個參數的前一個位置數字)

INTERVAL(N,N1,N2,N3,…)

Returns 0 if N < N1, 1 if N < N2 and so on or -1 if N is NULL. All arguments are treated as integers. It is required that N1 < N2 < N3 < … < Nn for this function to work correctly. This is because a binary search is used (very fast).

mysql> SELECT INTERVAL(23, 1, 15, 17, 30, 44, 200); (23小於30,30的位置是4,於是返回3)

-> 3

mysql> SELECT INTERVAL(10, 1, 10, 100, 1000);

-> 2

mysql> SELECT INTERVAL(22, 23, 30, 44, 200);

-> 0

在項目中的運用,業務場景:根據申報條件個數和申報類型進行去查詢每個分組的政策數量

SELECT

elt ( INTERVAL ( condition_count, 0, 3, 5.01, 8.01, 10.1 ), ‘少於3個條件’, ‘少於5個條件’, ‘少於8個條件’, ‘少於10個條件’, ‘多於10個條件’ ) AS difficult,

subsidy_type,

count( 1 ) num

FROM policy_info

GROUP BY difficult, subsidy_type

運行的結果

————————————————
版權聲明:本文爲CSDN博主「木木_亭」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/dyt443733328/article/details/82900153

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章