Below are the list data.
Code ItemCount Type Amount
----------------------------------------
B001 1 Dell 10.00
B001 1 Dell 10.00
B001 1 Apple 10.00
B001 2 Apple 20.00
B001 2 Apple 20.00
B114 1 Apple 30.50
B114 1 Apple 10.00
I need a result to group by code and by type and total the ItemCount
and get the grand total of the Amount
in every row.
Is this possible?
Code ItemCount Type Amount
----------------------------------------
B001 2 Dell 20.00
B001 5 Apple 50.00
B114 2 Apple 40.50
The use of COUNT() function in conjunction with GROUP BY is useful for characterizing our data under various groupings. A combination of same values (on a column) will be treated as an individual group.
We can use the group by multiple-column technique to group multiple records into a single record. All the records with the same values for the respective columns mentioned in the grouping criteria can be grouped as a single column using the group by multiple-column technique.
We can group the resultset in SQL on multiple column values. When we define the grouping criteria on more than one column, all the records having the same value for the columns defined in the group by clause are collectively represented using a single record in the query output.
If you need to add a group of numbers in your table you can use the SUM function in SQL. This is the basic syntax: SELECT SUM(column_name) FROM table_name; If you need to arrange the data into groups, then you can use the GROUP BY clause.
Please try:
SELECT
Code,
SUM(ItemCount) ItemCount,
Type,
SUM(Amount) Amount
FROM
YourTable
GROUP BY Code, Type
ORDER BY Code
This looks like homework.
(I swear I thought this was tagged as MySQL when I first looked at the question, but the title clearly shows MS SQL)
For MySQL, this query will return the specified resultset:
SELECT t.Code
, SUM(t.ItemCount) AS ItemCount
, t.Type
, s.Amount AS Amount
FROM mytable t
CROSS
JOIN ( SELECT SUM(r.Amount) AS Amount
FROM mytable r
) s
GROUP
BY t.Code
, t.Type
ORDER BY t.Code ASC, t.Type DESC
For other databases, remove For MySQL the backticks from around the column aliases.
If you need to preserve case, for Oracle, identifiers are enclosed in doublequotes. For SQL Server, identifiers are enclosed in square brackets. For MySQL identifiers are enclosed in backticks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With