2016-08-30 56 views
-2

如何在sql db2中檢查特定月份在特定月份中的特定季度。 像月1-4季度1喜歡比我想查個月-1是否是在今年的季度每季度檢查一次sql

+0

'Extract(month from column) '是ANSI SQL。或者你應該做'月(列)'。 – jarlh

+0

是的,我能夠從日期得到月份,但我必須檢查,該月屬於哪個季度.. – chaitanya

+0

'當monthval在(1,2,3),然後'q1'的情況下,當monthval在(4,5, 6),那麼'q2'... end' – jarlh

回答

0

試試這個

SELECT 
    MyDate, 
    CASE 
     WHEN MONTH(MyDate) BETWEEN 1 AND 3 THEN convert(char(4), YEAR(MyDate) - 1) + 'Q3' 
     WHEN MONTH(MyDate) BETWEEN 4 AND 6 THEN convert(char(4), YEAR(MyDate) - 1) + 'Q4' 
     WHEN MONTH(MyDate) BETWEEN 7 AND 9 THEN convert(char(4), YEAR(MyDate) - 0) + 'Q1' 
     WHEN MONTH(MyDate) BETWEEN 10 AND 12 THEN convert(char(4), YEAR(MyDate) - 0) + 'Q2' 
    END AS Quarter 
FROM 
    MyTable 
order by Quarter 

OR

SELECT 
    date 
    , CASE 
     WHEN MONTH(date) BETWEEN 7 AND 9 THEN 'First Quarter' 
     WHEN MONTH(date) BETWEEN 10 AND 12 THEN 'Second Quarter' 
     WHEN MONTH(date) BETWEEN 1 AND 3 THEN 'Third Quarter' 
     WHEN MONTH(date) BETWEEN 4 AND 6 THEN 'Fourth Quarter' 
    END AS quarter 
FROM Stuff 
1

DB2有一個內置的QUARTER function,做我認爲你想要的:

SELECT QUARTER(CURRENT TIMESTAMP) FROM SYSIBM.SYSDUMMY1