SQL語句分組查詢,elt,interval的使用


當我們使用SQL語句查詢的時候,總會遇到對區間進行分組查詢的需求的,這時候我們就需要用到interval和elt兩個函數來組合完成

 

首先介紹一下這兩個函數

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM