sql 中 case when 語法應用辦法。本站提示廣大學習愛好者:(sql 中 case when 語法應用辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是sql 中 case when 語法應用辦法正文
沒有,用case when 來取代就好了.
例如,上面的語句顯示中文年代
select getdate() as 日期,case month(getdate())
when 11 then '十一'
when 12 then '十二'
else substring('一二三四五六七八九十', month(getdate()),1)
end+'月' as 月份
CASE 能夠是 SQL 中被誤用最多的症結字之一。固然你能夠之前用過這個症結字來創立字段,然則它還具有更多用法。例如,你可以在 WHERE 子句中應用 CASE。
起首讓我們看一下 CASE 的語法。在普通的 SELECT 中,其語法以下:
SELECT <myColumnSpec> =
CASE
WHEN <A> THEN <somethingA>
WHEN <B> THEN <somethingB>
ELSE <somethingE>
END
在下面的代碼中須要器具體的參數取代尖括號中的內容。上面是一個簡略的例子:
USE pubs
GO
SELECT
Title,
'Price Range' =
CASE
WHEN price IS NULL THEN 'Unpriced'
WHEN price < 10 THEN 'Bargain'
WHEN price BETWEEN 10 and 20 THEN 'Average'
ELSE 'Gift to impress relatives'
END
FROM titles
ORDER BY price
GO
這是 CASE 的典范用法,然則應用 CASE 其實可以做更多的工作。比喻說上面的 GROUP BY 子句中的 CASE:
SELECT 'Number of Titles', Count(*)
FROM titles
GROUP BY
CASE
WHEN price IS NULL THEN 'Unpriced'
WHEN price < 10 THEN 'Bargain'
WHEN price BETWEEN 10 and 20 THEN 'Average'
ELSE 'Gift to impress relatives'
END
GO
你乃至還可以組合這些選項,添加一個 ORDER BY 子句,以下所示:
USE pubs
GO
SELECT
CASE
WHEN price IS NULL THEN 'Unpriced'
WHEN price < 10 THEN 'Bargain'
WHEN price BETWEEN 10 and 20 THEN 'Average'
ELSE 'Gift to impress relatives'
END AS Range,
Title
FROM titles
GROUP BY
CASE
WHEN price IS NULL THEN 'Unpriced'
WHEN price < 10 THEN 'Bargain'
WHEN price BETWEEN 10 and 20 THEN 'Average'
ELSE 'Gift to impress relatives'
END,
Title
ORDER BY
CASE
WHEN price IS NULL THEN 'Unpriced'
WHEN price < 10 THEN 'Bargain'
WHEN price BETWEEN 10 and 20 THEN 'Average'
ELSE 'Gift to impress relatives'
END,
Title
GO
留意,為了在 GROUP BY 塊中應用 CASE,查詢語句須要在 GROUP BY 塊中反復 SELECT 塊中的 CASE 塊。
除選擇自界說字段以外,在許多情形下 CASE 都異常有效。再深刻一步,你還可以獲得你之前以為弗成能獲得的分組排序成果集。