Author |
Topic |
chaoys
Starting Member
2 Posts |
Posted - 2010-08-03 : 14:37:28
|
Hi, all,I try to covert month to quarter and sum up all the quarter sales from one table, however I keep getting compiling errors,Table1:FIPS year month salesX 2003 1 50120X 2003 1 30520X 2003 1 49998I would like my output to be,FIPS year month salesX 2003 1 130638please find my codes below,SELECT fips, year, quar = CASE WHEN month BETWEEN 1 and 3 THEN 1 WHEN month BETWEEN 4 and 6 THEN 2 WHEN month BETWEEN 7 and 9 THEN 3 WHEN month BETWEEN 10 and 12 THEN 4 END, SUM(sales) AS salesFROM table1WHERE (year BETWEEN 2003 AND 2007)GROUP BY fips, year, quarORDER BY fips, year, quarAny thoughts? |
|
jimf
Master Smack Fu Yak Hacker
2875 Posts |
Posted - 2010-08-03 : 14:48:37
|
It's just in your group by clause, SQL doesn't recognize quar as a column yet, but notice that it does in the order by statementECLARE @Table1 TABLE (FIPS char(1),[year] int ,[month] int, sales int)INSERT INTO @Table1SELECT 'X', 2003, 1, 50120 UNION ALLSELECT 'X', 2003, 1, 30520 UNION ALLSELECT 'X', 2003, 1, 49998 SELECT fips, year, quar = CASEWHEN month BETWEEN 1 and 3 THEN 1WHEN month BETWEEN 4 and 6 THEN 2WHEN month BETWEEN 7 and 9 THEN 3WHEN month BETWEEN 10 and 12 THEN 4 END, SUM(sales) AS salesFROM @table1WHERE (year BETWEEN 2003 AND 2007)GROUP BY fips, year, CASEWHEN month BETWEEN 1 and 3 THEN 1WHEN month BETWEEN 4 and 6 THEN 2WHEN month BETWEEN 7 and 9 THEN 3WHEN month BETWEEN 10 and 12 THEN 4 ENDORDER BY fips, year, quar JimEveryday I learn something that somebody else already knew |
 |
|
chaoys
Starting Member
2 Posts |
Posted - 2010-08-03 : 15:00:48
|
quote: Originally posted by jimf It's just in your group by clause, SQL doesn't recognize quar as a column yet, but notice that it does in the order by statementECLARE @Table1 TABLE (FIPS char(1),[year] int ,[month] int, sales int)INSERT INTO @Table1SELECT 'X', 2003, 1, 50120 UNION ALLSELECT 'X', 2003, 1, 30520 UNION ALLSELECT 'X', 2003, 1, 49998 SELECT fips, year, quar = CASEWHEN month BETWEEN 1 and 3 THEN 1WHEN month BETWEEN 4 and 6 THEN 2WHEN month BETWEEN 7 and 9 THEN 3WHEN month BETWEEN 10 and 12 THEN 4 END, SUM(sales) AS salesFROM @table1WHERE (year BETWEEN 2003 AND 2007)GROUP BY fips, year, CASEWHEN month BETWEEN 1 and 3 THEN 1WHEN month BETWEEN 4 and 6 THEN 2WHEN month BETWEEN 7 and 9 THEN 3WHEN month BETWEEN 10 and 12 THEN 4 ENDORDER BY fips, year, quar JimEveryday I learn something that somebody else already knew
Lifesaver, this is great, it worked!Thank you very much, Jim! |
 |
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2010-08-03 : 15:22:20
|
SELECT (MONTH - 1) / 3 + 1 AS Quarter N 56°04'39.26"E 12°55'05.63" |
 |
|
|
|
|