SQL: Grouping by two colums and sum another


SQL: Grouping by two colums and sum another
I am trying to sum up the cost column and then group by the type and then the date column. It should be very straight forward but after I apply the sum aggregate and try to group by the two columns I keep ending up with either too few or two many results and the summed total is wrong in each case.
If I have a table as such below:
<table >
<tbody>
<tr>
<td> Date</td>
<td> Type</td>
<td> Cost</td>
</tr>
<tr>
<td> Jan 01</td>
<td> TV</td>
<td> 20</td>
</tr>
<tr>
<td> Jan 01</td>
<td> TV</td>
<td> 25</td>
</tr>
<tr>
<td> Jan 01</td>
<td>Phone </td>
<td> 10</td>
</tr>
<tr>
<td> Jan 01</td>
<td> Phone</td>
<td> 20</td>
</tr>
<tr>
<td> Jan 02</td>
<td> TV</td>
<td> 30</td>
</tr>
<tr>
<td> Jan 02</td>
<td> Phone</td>
<td> 80</td>
</tr>
<tr>
<td> Jan 02</td>
<td> Phone</td>
<td> 20</td>
</tr>
<tr>
<td> Jan 03</td>
<td> TV</td>
<td>20 </td>
</tr>
<tr>
<td> Jan 03</td>
<td> TV</td>
<td> 40</td>
</tr>
<tr>
<td> Jan 03</td>
<td> Other</td>
<td> 10</td>
</tr>
</tbody>
</table>
What is the proper group by function to get the output equivalent to:
<table >
<tbody>
<tr>
<td> Date</td>
<td> Type</td>
<td> Cost</td>
</tr>
<tr>
<td> Jan 01</td>
<td> TV</td>
<td> 45</td>
</tr>
<tr>
<td> Jan 01</td>
<td>Phone </td>
<td> 30</td>
</tr>
<tr>
<td> Jan 02</td>
<td> TV</td>
<td> 30</td>
</tr>
<tr>
<td> Jan 02</td>
<td> Phone</td>
<td> 100</td>
</tr>
<tr>
<td> Jan 03</td>
<td> TV</td>
<td>60 </td>
</tr>
<tr>
<td> Jan 03</td>
<td> Other</td>
<td> 10</td>
</tr>
</tbody>
</table>
I am trying to sum the 'Cost' column but I keep ending up with incorrect results
* Edit *
The accepted answer is correct, but what was going wrong for me referred to two other columns which needed to be filtered beforehand to get the expected output.
1 Answer
1
You can try group by
and sum
function.
group by
sum
When you use an aggregate function, you need to add the non-aggregate columns in group by
.
group by
SELECT date,type,Sum(Cost) Cost
FROM T
group by date,type
sqlfiddle
[Results]:
| date | type | Cost |
|--------|-------|-----------|
| Jan 01 | Phone | 30 |
| Jan 01 | TV | 45 |
| Jan 02 | Phone | 100 |
| Jan 02 | TV | 30 |
| Jan 03 | Other | 10 |
| Jan 03 | TV | 60 |
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Comments
Post a Comment