2012-01-31 98 views
-1

我似乎无法按多个数据字段进行分组,并对特定的分组列进行求和。SELECT datafields with multiple groups and sum

我想将人员分组到客户,然后将客户分组为价格,然后合计价格。合计金额(价格)最高的人应按升序列出。

例子:

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 

我想要的结果是:

**BOB:** 
Orange, $2230 

**GREG:** 
green, $360 
blue,$170 

The colors are the customer, that GREG and Bob handle. Each color has a price. 
+3

为什么'green'应该与'360'匹配并且用'170'与'blue'匹配?而不是相反呢? – 2012-01-31 18:35:41

+0

颜色是顾客,GREG和Bob处理。每种颜色都有一个价格。 – tdjfdjdj 2012-01-31 18:39:35

+0

那么,你是说每个顾客都有一个价格? – 2012-01-31 18:41:45

回答

4

我可以看到两个问题。其中一个有点挑剔,一个是非常基础的。在SQL数据


介绍

SQL返回表格数据集。它无法返回带标题的子集,查找某个数据透视表。

的意思是这是不可能的......

**BOB:** 
Orange, $2230 

**GREG:** 
green, $360 
blue, $170 

但是这可能...

Bob, Orange, $2230 
Greg, Green, $360 
Greg, Blue, $170 


相关数据

我可以直观地看到你如何将数据联系在一起......

table customer     table invoice 
--------------     ------------- 
customer | common_id   person | price |common_id 
green  2     greg  360  2 
blue   2     greg  170  2 
orange  1     bob  2330  1 

但SQL没有任何隐含的排序。如果一个表达可以声明它们是相关的,那么事物只能是相关的。例如,下面同样有可能...

table customer     table invoice 
--------------     ------------- 
customer | common_id   person | price |common_id 
green  2     greg  170  2  \ These two have 
blue   2     greg  360  2 /been swapped 
orange  1     bob  2330  1 

这意味着你需要规则(以及可能的其他字段)明确宣称其customer记录匹配其invoice记录,特别是当有两个倍数与相同的common_id

规则的一个例子可能是,最低价格总是按字母顺序与第一个客户匹配。不过,如果你有在customercommon_id = 2记录发生,但只有invoicecommon_id = 2记录?或者记录的数量总是匹配,你是否强制执行?

很有可能您需要额外的一块(或多块)信息到了解哪些记录相互关联。

0

你应该使用除了和你的所有选定字段组那么也许函数GROUP_CONCAT(MySQL的)可以帮助你在串联结果行组子句

+0

他没有使用mysql。 – deutschZuid 2012-01-31 20:14:51

0

我不知道你怎么可能做到这一点。 Greg有2种颜色和2种价格,你如何确定哪种颜色与哪种颜色搭配?

Greg Blue 170或​​Greg Blue 360​​ ????或将绿色附加到任何价格?

我认为颜色需要有独特的身份识别符,与个人独特的身份识别符分开。

只是一个想法。