เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

การสร้างหลายกลุ่มด้วย CASE

ในแบบฝึกหัดนี้ จะเขียนคำสั่ง CASE เพื่อจัดกลุ่มค่าในคอลัมน์ DurationSeconds ออกเป็น 5 กลุ่ม ตามช่วงค่าดังต่อไปนี้:

DurationSeconds SecondGroup
<= 120 1
> 120 and <= 600 2
> 600 and <= 1200 3
> 1201 and <= 5000 4
For all other values 5

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

SQL Server ระดับกลาง

ดูคอร์ส

คำแนะนำการฝึกหัด

สร้างคอลัมน์ใหม่ชื่อ SecondGroup โดยใช้ค่าจากคอลัมน์ DurationSeconds ตามช่วงค่าที่กำหนดไว้ข้างต้น

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

-- Complete the syntax for cutting the duration into different cases
SELECT DurationSeconds, 
-- Start with the 2 TSQL keywords, and after the condition a TSQL word and a value
      ___ ___ (DurationSeconds <= 120) ___ ___
-- The pattern repeats with the same keyword and after the condition the same word and next value          
       ___ (DurationSeconds > 120 AND DurationSeconds <= 600) ___ ___
-- Use the same syntax here             
       ___ (DurationSeconds > 601 AND DurationSeconds <= 1200) ___ ___
-- Use the same syntax here               
       ___ (DurationSeconds > 1201 AND DurationSeconds <= 5000) ___ ___
-- Specify a value      
       ELSE ___ 
       END AS SecondGroup   
FROM Incidents
แก้ไขและรันโค้ด