I cant seem to group by multiple data fields and sum a particular grouped column.
I want to group Person to customer and then group customer to price and then sum price. The person with the highest combined sum(price) should be listed in ascending order.
Example:
table customer
-----------
customer | common_id
green 2
blue 2
orange 1
table invoice
----------
person | price | common_id
bob 2330 1
greg 360 2
greg 170 2
SELECT DISTINCT
min(person) As person,min(customer) AS customer, sum(price) as price
FROM invoice a LEFT JOIN customer b ON a.common_id = b.common_id
GROUP BY customer,price
ORDER BY person
The results I desire are:
**BOB:**
Orange, $2230
**GREG:**
green, $360
blue,$170
The colors are the customer, that GREG and Bob handle. Each color has a price.
There are two issues that I can see. One is a bit picky, and one is quite fundamental.
Presentation of data in SQL
SQL returns tabular data sets. It’s not able to return sub-sets with headings, looking something a Pivot Table.
The means that this is not possible…
But that this is possible…
Relating data
I can visually see how you relate the data together…
But SQL doesn’t have any implied ordering. Things can only be related if an expression can state that they are related. For example, the following is equally possible…
This means that you need rules (and likely additional fields) that explicitly state which
customerrecord matches whichinvoicerecord, especially when there are multiples in both with the samecommon_id.An example of a rule could be, the lowest price always matches with the first customer alphabetically. But then, what happens if you have three records in
customerforcommon_id = 2, but only two records ininvoiceforcommon_id = 2? Or do the number of records always match, and do you enforce that?Most likely you need an extra piece (or pieces) of information to know which records relate to each other.