SQL Server How to get group-by result and individual rows from table

gpnt7bae  于 2023-10-15  发布在  其他
关注(0)|答案(3)|浏览(165)

Currently I have a table like this:
| Partno | Total |
| ------------ | ------------ |
| 0100 | 50 |
| 0100 | 200 |
| 0100 | 300 |
| 0450 | 100 |
| 0450 | 350 |
| 0600 | 250 |

I'd like to get a result like this:

PartnoTotal
0100550
010050
0100200
0100300
0450450
0450100
0450350
0600250
0600250

Where the italic rows are grouped-by on Partno. How can I get this result using a query?

Right now I have to do it using a master-detail grid, because I can't fit it in 1 query.

g2ieeal7

g2ieeal71#

This will retrieves all rows from the table and also includes additional rows that represent the sum of Total values for each unique Partno :

SELECT Partno, Total
FROM mytable
UNION ALL
SELECT Partno, SUM(Total)
FROM mytable
GROUP BY Partno
ORDER BY Partno, Total DESC

Demo here

z3yyvxxp

z3yyvxxp2#

Seems like you need to use GROUPING SETS here. Note that if you have 2 or more rows with the same value of Total they will be aggregated; if that's the case you should be using your primary key column instead (which is omitted in the sample data):

SELECT Partno,
       SUM(Total) AS Total
FROM (VALUES('0100',50),
            ('0100',200),
            ('0100',300),
            ('0450',100),
            ('0450',350),
            ('0600',250))V(Partno,Total)
GROUP BY GROUPING SETS((PartNo,Total),
                       (PartNo))
ORDER BY V.Partno,
         V.Total;
h9a6wy2h

h9a6wy2h3#

You can achieve it by using UNION ALL between two queries:

select partno,total,1 as sort_col 
 from my_table

union all 

select partno,sum(total) total,0  
 from my_table group by partno

order by partno,sort_col

相关问题