Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Combining results from multiple tables in TIP
Message
From
05/08/2014 19:56:36
 
General information
Forum:
Microsoft SQL Server
Category:
SQL syntax
Environment versions
SQL Server:
SQL Server 2014
Application:
Web
Miscellaneous
Thread ID:
01605208
Message ID:
01605218
Views:
32
>>I should know how to do this but today my mind is blank. Can someone help please?
>>Here are 4 queries:
>>
>>select sum(amount) as igabudget, fundtype, phase from RTA_IGABudgets where TipID=@TipID group by Fundtype, phase
>> 
>>select sum(amount) as expended,  fundtype, phase from TIP_Ledger2 where TipID=@TipID and fisyear<@Tipyear group by FundType, phase
>>
>>select sum(amount)*1000 as programmed, fundtype, phase from TIP_ApprovedFunding where TipID=@TipID and year<=@tipyear group by fundtype, phase 
>>
>>select SUM(amount)*1000 as futureprogrammed, fundtype, phase from TIP_ApprovedFunding where TipID=@TipID and YEAR>@Tipyear group by FundType, PHASE
>>
>>
>>I want to combine the results of these into a single table with one row for each combination of Fundtype & Phase. So the result table has the columns
>>IGABudget
>>FundType
>>Phase
>>Programmed
>>FutureProgrammed
>>
>>I have tries various combinations of JOINS, UNIONS, and DISTINCTS, but I can't seem to get it right. The problem is that not all combinations of fundtype and phase exist in all the tables. So we first have to pull those out and then do the math that goes with them.
>>
>>Thanks
>
>
>
>SELECT fundtype,
>       phase,
>       SUM(CASE WHEN Type = 1 THEN Amount END) AS igabudget,
>       SUM(CASE WHEN Type = 2 THEN Amount END) AS expended,
>       SUM(CASE WHEN Type = 3 THEN Amount END) AS programmed,
>       SUM(CASE WHEN Type = 4 THEN Amount END) AS futureprogrammed
>FROM (select amount as Amount,
>             fundtype,
>             phase,
>             1 AS Type
>      from RTA_IGABudgets 
>      where TipID=@TipID
>      UNION ALL
>      select amount as Amount,
>             fundtype,
>             phase,
>             2 AS Type
>      from TIP_Ledger2
>      where TipID=@TipID
>        and fisyear<@Tipyear
>      UNION ALL      
>      select amount*1000 as Amount,
>             fundtype,
>             phase,
>             3 AS Type
>       from TIP_ApprovedFunding
>       where TipID=@TipID
>         and year<=@tipyear
>       UNION ALL
>       select amount*1000 as Amount,
>              fundtype,
>              phase,
>              4 AS Type
>        from TIP_ApprovedFunding
>        where TipID=@TipID 
>          and YEAR>@Tipyear
>      ) Test
>group by FundType, PHASE      
>
>
>NOT TESTED!!!


Thank you Borislav. I was trying something similar with the UNIONs but missed the alias and wondered why it wouldn't work.
Much appreciated.
Previous
Reply
Map
View

Click here to load this message in the networking platform