How use case in this sql queries [Resolved]

Posted by Cpatil1000 under Sql Server on 2/19/2016 | Points: 10 | Views : 579 | Status : [Member] | Replies : 2
In this query I am trying getting result with fincial year but I am using month instead of date.
I am passing start month and end month e. between 4 to 12. But if I passed month 1 or 2, 3 then it getting problem. So how it is possible use case in the where clause following sql query. Other wise my sql squery is getting large because there have so many field which is I require as bellow…
I ) if month between 4 to 12
Where Year(NWWDD.DAILY_DATE) = 2012
And Month(NWWDD.DAILY_DATE) >= 4 and Month(NWWDD.DAILY_DATE) <= 12
2) if month between 4 to 12 and month select ( 1 or 2 or 3)
Where Year(NWWDD.DAILY_DATE) = 2012
And (((Month(NWWDD.DAILY_DATE) Between 4 and 12) and Year(NWWDD.DAILY_DATE) = 2012)
oR (Month(NWWDD.DAILY_DATE) <= 1 and Year(NWWDD.DAILY_DATE) = 2012))

Declare @MONTH int
Set @MONTH = 5
-- PREVIOUS_YEAR_COLLECTION
If(@MONTH in (1,2,3))
Begin
Select NWWDD.REGION_ID, NWWRM.REGION, Sum(NWWDD.PER_DAY_COLLECTION) As 'PREVIOUS_YEAR_COLLECTION'
From NEW_WATER_WORK_DAILY_DETAIL NWWDD
Inner Join NEW_WATER_WORK_REGION_MASTER NWWRM On NWWRM.ID = NWWDD.REGION_ID
Inner Join NEW_WATER_WORK_MASTER NWWM On NWWM.ID = NWWDD.WW_ID
Where Year(NWWDD.DAILY_DATE) = 2012
And (((Month(NWWDD.DAILY_DATE) Between 4 and 12) and Year(NWWDD.DAILY_DATE) = 2012)
oR (Month(NWWDD.DAILY_DATE) <= 1 and Year(NWWDD.DAILY_DATE) = 2012))
Group by NWWDD.REGION_ID,NWWRM.REGION
Order by NWWDD.REGION_ID
End
Else
Begin
Select NWWDD.REGION_ID, NWWRM.REGION, Sum(NWWDD.PER_DAY_COLLECTION) As 'PREVIOUS_YEAR_COLLECTION'
From NEW_WATER_WORK_DAILY_DETAIL NWWDD
Inner Join NEW_WATER_WORK_REGION_MASTER NWWRM On NWWRM.ID = NWWDD.REGION_ID
Inner Join NEW_WATER_WORK_MASTER NWWM On NWWM.ID = NWWDD.WW_ID
Where Year(NWWDD.DAILY_DATE) = 2012
And Month(NWWDD.DAILY_DATE) >= 4 and Month(NWWDD.DAILY_DATE) <= 12
Group by NWWDD.REGION_ID,NWWRM.REGION
Order by NWWDD.REGION_ID
End




Responses

Posted by: Poster on: 2/19/2016 [Member] Starter | Points: 50

Up
1
Down

Resolved
Hmm.... large query and custom requirement.

Better learn using Case statement. Here is the quick result I found on google - http://techfunda.com/howto/199/case-statement-in-sql-server.

Thanks

Cpatil1000, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Amatya on: 2/22/2016 [Member] Silver | Points: 25

Up
0
Down
Do with Conditions and Temp Tables
Thanks

Feel free to share informations 9731764134
mail Id ' adityagupta200@gmail.com
Thanks

Cpatil1000, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response