2015-08-24 390 views
0

有條件地顯示值我有一個非常簡單的查詢,但我需要它,這樣,如果Conditional少於兩則Title應顯示爲全部大寫。以大寫字母

SELECT DISTINCT Title, COUNT(Title) AS NumberOfTitles 
FROM Table 
WHERE Conditional < 3 
GROUP BY Title 
ORDER BY Title 

我試過CASE等等,但似乎可以得到它的工作

我還需要標題設置爲「主」如果有條件= 1

回答

2
SELECT 
case when conditional = 1 then 'MAIN' 
when conditional <> 1 and conditional < 2 then UPPER(Title) 
else Title end as Title 
, COUNT(Title) AS NumberOfTitles 
FROM Table 
GROUP BY case when conditional = 1 then 'MAIN' 
     when conditional <> 1 and conditional < 2 then UPPER(Title) 
     else Title end 
ORDER BY case when conditional = 1 then 'MAIN' 
     when conditional <> 1 and conditional < 2 then UPPER(Title) 
     else Title end 

你可以試試THI與case聲明。

+0

打我吧,這就是我會做太 –

+0

完美謝謝 – HolyUnicow

+0

我如果條件爲1,還需要將標題更改爲「主」,我可以使用相同的情況還是需要輔助? – HolyUnicow

1

我想包在一個公共表表達式的邏輯,以避免在group byorder by條款重蹈覆轍:

WITH cte AS (
    SELECT 
     CASE WHEN conditional < 2 THEN UPPER(Title) 
      ELSE Title 
     END AS Title 
    FROM Table 
) 

SELECT Title, COUNT(Title) AS NumberOfTitles 
FROM cte 
GROUP BY Title 
ORDER BY Title;