SQL語句重的判斷

2021-10-04 20:52:32 字數 1670 閱讀 4085

雖然我早就知道sql語句的強大之處,正好比資料分析師們什麼都不會,單憑一門sql語言就出來各種各樣的資料。但我也從來沒想到自己會有一天在sql語句裡頭進行判斷處理。

起因:老師讓給查一下每個人每學期總共有多少學時的課,他想看看每週每個人大概的課程數。剛好 我們的課表系統的資料結構是每一節課一條資料,如果時間分為單雙周或者是時間段分開了則存成不同的元組,所以我需要做的就是把某個人的所有課程資訊先groupby一下人命,然後每一節課的結束週數減去開始週數,最後求個sum就可以獲得到一學期的課了。聽起來沒問題,寫起來也很簡單。

```select course.user_name,user.user_class,user.department, sum(course.end_week - course.start_week + 1) as total

from timetable.course

inner join user 

on user.dd_id = course.dd_id

where course.is_delete = 0

group by user_name

order by total desc

```![初步結果](

然後同學見到了我隨口一問,才發現,自己忽略了單雙周的兩種情況,單週和雙周計算課時的方法時不一樣的,需要除以2或者除以2再加一,這就需要用到判斷了啊。。

實際上挺慌的,怕沒法完美完成任務,然後就去bing一下,查mysql條件語句,竟然真的有能夠在mysql裡面進行條件查詢的語句天吶。瞬間變得激動了起來,也不知道為什麼,寫原生**(sql)總是讓我感到很激動,比jpa或者是其他jdbc什麼激動許多。然後開始上手用,嘗試著使用case when then,把我查到的例子貼上過來吧~![出自他人回答](

瞬間sql語句變得更加靈活了,然後經過各種測試編寫,除了最後sum函式應該包括的內容卡了我一下,其他的就順理成章的出來了,很好。

```select course.user_name,user.user_class,user.department, 

sum(case course.type 

when 1 then (course.end_week - course.start_week + 2)/2

when 2 then (course.end_week - course.start_week)/2 + 1

when 0 then course.end_week - course.start_week + 1

end) as total,

sum(case course.type 

when 1 then (course.end_week - course.start_week + 2)/2

when 2 then (course.end_week - course.start_week)/2 + 1

when 0 then course.end_week - course.start_week + 1

end)/19 as perweek

from timetable.course

inner join user 

on user.dd_id = course.dd_id

where course.is_delete = 0

group by user_name

order by total desc

```![最終結果](

SQL條件判斷語句

select case when price is null then not yet priced when price 10 then very reasonable title when price 10 and price 20 then coffee table title else ex...

sql 語句加判斷規則

假設現在 傳進來2個引數 isput isplus 值都為 1,0 語句大概如下 select from table t where isput 0 and isplus 0 or isput 1 and isplus 1 and t.fmodifyno is not null or isput 1...

SQL語句判斷奇偶數

題目來自 牛客sql篇.題目描述 有乙個員工表employees簡況如下 請你查詢employees表所有emp no為奇數,且last name不為mary的員工資訊,並按照hire date逆序排列,以上例子查詢結果如下 方法一 使用mod mod a,b 在sql中的意思是 a b 的餘數 m...