Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Can I use a GROUP BY without having to group on all the fields I'm trying to select?I have a customer table and a sales table and I query them something like this:SELECT custDet.id, sales.tot, sum(sales.tot) from custDet, salesWHERE sales.custID = custDet.idGROUP BY custDet.id, sales.totwhich would produce something like thisID | TOT | SUM~~~~~~~~~~~~~~1 | 20 | 201 | 50 | 501 | 15 | 154 | 10 | 104 | 12 | 12But what I really want is the SUM to total the sales.tot column for the whole custDet.id group rather than for each line. I know it's doing it per line because I have the sales.tot in the GROUP BY, but I can't remove it so what do I do? What I'm looking for is results like this:ID | TOT | SUM~~~~~~~~~~~~~~1 | 20 | 851 | 50 | 851 | 15 | 854 | 10 | 224 | 12 | 22So the SUM reflects the total sales per group. I need to do it this way because I want to be able to sort the table by the SUM column but still display all sales totals.Any ideas?Thanks...
byrmol
Shed Building SQL Farmer
1591 Posts
Posted - 2003-05-05 : 02:21:30
You need a subquery.... Not tested or parsed...
SELECT CDid, sales.tot, (Select Sum(Tot) from Sales where CustID = CD.ID GROUP BY custID) AS Customertotalfrom custDet AS CD, sales WHERE sales.custID = CD.id GROUP BY CDid, sales.tot