Solved

How can I view detalis and sum info in same query

Posted on 2014-02-03
3
187 Views
Last Modified: 2014-02-03
Hello, I have one table:
[ID]      [Group_ID]       [Amount]
1      1      10
2      1      20
3      2      5


I want to make a query that show details, but also sum by Group_ID.

[ID]       [Amount]
1      10
2      20
      30 (Sum group id 1)
3      5
      5 (Sum group id 2)

Can some help me? (I use MS SQL server 2008 R2)
0
Comment
Question by:tselectro
3 Comments
 
LVL 65

Accepted Solution

by:
Jim Horn earned 300 total points
Comment Utility
Here's an example from an article I wrote on SQL Server GROUP BY solutions.
Scroll down to #5.

In your case, where the example has a subquery that returns the Max(), you'll need a subquery that returns a Sum().

Something like..
SELECT yt.ID, yt.Group_ID, yt.Amount, yt_total.the_sum
FROM your_table yt
JOIN (
   SELECT Group_ID, Sum(Amount) as the_sum
   FROM your_table
   GROUP BY Group_ID ) yt_total ON yt.Group_ID = yt_total.Group_ID

Open in new window

Guessing for readability it would be better to include the Group_ID in the query results.
0
 
LVL 69

Assisted Solution

by:ScottPletcher
ScottPletcher earned 200 total points
Comment Utility
SELECT
    CASE WHEN ID_ = 'Total' THEN '' ELSE ID_ END AS ID, Amount
FROM (
    SELECT CAST(ID AS varchar(10)) AS ID_, Group_ID, Amount
    FROM dbo.tablename
    UNION ALL
    SELECT 'Total', Group_ID, SUM(Amount)
    FROM dbo.tablename
    GROUP BY Group_ID
) AS derived
ORDER BY
    Group_ID, ID_
0
 

Author Closing Comment

by:tselectro
Comment Utility
Thank you very much!
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Having an SQL database can be a big investment for a small company. Hardware, setup and of course, the price of software all add up to a big bill that some companies may not be able to absorb.  Luckily, there is a free version SQL Express, but does …
Let's review the features of new SQL Server 2012 (Denali CTP3). It listed as below: PERCENT_RANK(): PERCENT_RANK() function will returns the percentage value of rank of the values among its group. PERCENT_RANK() function value always in be…
Via a live example, show how to shrink a transaction log file down to a reasonable size.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now