Help with SQL Query

  • Consider i have the below table structure

    create table #temp(id int,entity nvarchar(50))

    insert into #temp values(1,'Candy')

    insert into #temp values(2,'Chocolate')

    create table #temp2(name nvarchar(50),id int,value int)

    insert into #temp2 values('Johnson',1,50)

    insert into #temp2 values('Johnson',2,70)

    insert into #temp2 values('Darick',1,30)

    insert into #temp2 values('Darick',2,90)

    I want the output as

    nameid candy chocolate

    Johnson1 50 70

    Darick1 30 90

    I tried using pivot but could not acheive what i want. And coding @ afternoon is :doze:

  • seems to be complex, but you can try this..

    SELECT pv.NAME , min(ID) id, Candy , Chocolate from (

    SELECT Name , Candy , Chocolate from

    (SELECT

    Name, [entity] , value

    FROM #temp a INNER JOIN #temp2 b on a.id = b.id

    ) x

    pivot

    (

    sum (value)

    FOR [entity] IN (Candy , Chocolate)

    ) p

    ) as pv Left Join #temp2 a on a.name = pv.name

    group by pv.NAME , Candy , Chocolate



    Praveen D'sa
    MCITP - Database Administrator 2008
    http://sqlerrors.wordpress.com

  • Probably the best tool for this is a dynamic cross-tab. Jeff Moden has an excellent article here[/url]. If after reading the article you are still having difficulty, post back.

    “Write the query the simplest way. If through testing it becomes clear that the performance is inadequate, consider alternative query forms.” - Gail Shaw

    For fast, accurate and documented assistance in answering your questions, please read this article.
    Understanding and using APPLY, (I) and (II) Paul White
    Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply