TheSQLGuru
3/28/2007 3:20:00 PM
Check for an article by Itzik Ben-Gan in SQL Mag recently on dynamic
PIVOTing.
You cannot 'add' a cursor to the CASE statement code given. Also, you will
somehow HAVE to get the DISTINCT list of values you want to cross-tab by.
Gonna be quite inefficient I am betting!
--
TheSQLGuru
President
Indicium Resources, Inc.
"Ryan" <Tyveil@newsgroups.nospam> wrote in message
news:%23zPYKeUcHHA.4312@TK2MSFTNGP05.phx.gbl...
> Thanks for the reply. Unfortunately this won't entirely work because
> there are not a set amount of sources (SourceA, SourceB, etc). I want as
> many (Source) columns as there are records in the Source table. I imagine
> I need some sort of cursor.. how would I add that logic to this query?
>
> "xyb" <xiangyuanbo@gmail.com> wrote in message
> news:1175090725.325099.249030@l77g2000hsb.googlegroups.com...
> On 3ÔÂ28ÈÕ, ÏÂÎç9ʱ39·Ö, "Ryan" <Tyv...@newsgroups.nospam> wrote:
>> I need help writing a cross-tab type query.
>> I want to show the details of each project, and a column for each funding
>> source (whether that project/funding source has an amount or not)
>> So the columns would be:
>> ProjectID
>> ProjectName
>> ProjectDesc
>> SourceAAmount
>> SourceBAmount
>> SourceCAmount
>>
>> Heres the underlying data structure:
>>
>> Table1 (Project Details)
>> ProjectID (PK)
>> ProjectName
>> ProjectDesc
>> etc.
>>
>> Table2 (Amount)
>> FundingID (PK)
>> SourceID (FK)
>> ProjectID (FK)
>> FundingAmount
>>
>> Table3 (Funding Sources)
>> SourceID
>> SourceName
>>
>> If an amount doesn't exist for the particular funding source I want the
>> value to be 0 (IE no record in table 2 for that particular
>> project/funding
>> source)
>> How would I accomplish this?
>>
>> Thanks,
>> Ryan
>
> select
> t1.ProjectID,
> t1. ProjectName,
> t1.ProjectDesc,
> SourceAAmount = isnull(sum(case when t3.SourceName = 'a' then
> t2.FundingAmount else 0 end),0),
> SourceBAmount = isnull(sum(case when t3.SourceName = 'b' then
> t2.FundingAmount else 0 end),0),
> SourceCAmount = isnull(sum(case when t3.SourceName = 'c' then
> t2.FundingAmount else 0 end),0)
> from t1 join t2 on t1.ProjectID = t2.ProjectID left join t3 on
> t2.SourceID = t3.SourceID
> group by t1.ProjectID,
> t1. ProjectName,
> t1.ProjectDesc,
> t3.SourceName
>
>