Group by select problem

  • Hi all

    have developed my library project counter problem when I want to get sum

    book status (in , out ,lost,damage and removed) of the same title from master Book table vs details Book table in one row.Master book table link with detail table field bookID and their status field on the book details have 1=in,2=out,3=lost,4=damage,5=removed .I tried to use group by method but got sum their status of same title different rows

    Please need you help

    thank in advanced

  • Maybe this gets you started...

    Select M.BookId, D.[status], count(*) as NumberOfOccurrences

    from [master Book table] M

    inner join [details Book table] D

    on M.bookID = D.BookId

    Group by M.BookId, D.Status

    Johan

    Learn to play, play to learn !

    Dont drive faster than your guardian angel can fly ...
    but keeping both feet on the ground wont get you anywhere :w00t:

    - How to post Performance Problems
    - How to post data/code to get the best help[/url]

    - How to prevent a sore throat after hours of presenting ppt

    press F1 for solution, press shift+F1 for urgent solution 😀

    Need a bit of Powershell? How about this

    Who am I ? Sometimes this is me but most of the time this is me

  • thank for you answer

    but I hope you

    did not get me well I want to get sum of status Book i.e In book,out Book Lost book,Damage and Removed as table fields for each title book

    thanks in advance

  • Sounds like you might be looking for a "pivot query" solution. Something like:

    Select M.BookId, M.booktitle,

    sum(case when d.status=1 then 1 else 0 end) as TotalIn,

    sum(case when d.status=2 then 1 else 0 end) as TotalOut,

    sum(case when d.status=3 then 1 else 0 end) as TotalLost,

    sum(case when d.status=4 then 1 else 0 end) as TotalDamaged,

    sum(case when d.status=5 then 1 else 0 end) as TotalRemoved

    from [master Book table] M

    inner join [details Book table] D

    on M.bookID = D.BookId

    Group by M.BookId, M.booktitle

    ----------------------------------------------------------------------------------
    Your lack of planning does not constitute an emergency on my part...unless you're my manager...or a director and above...or a really loud-spoken end-user..All right - what was my emergency again?

  • thanks a lot its work

  • Hello,

    I have a similar problem. The difference is the number of sums returned is variable, i.e. it is determined by an input parameter.

    How do I code this?

  • Could you post this in a new thread and post your table structure and some sample data? hard to tell without some details.

Viewing 7 posts - 1 through 6 (of 6 total)

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