SQL:如何从GROUP BY语句中获取更多信息

时间:2010-08-05 08:32:16

标签: sql group-by

考虑以下SQL语句:

SELECT 
invoice.customer_name, 
invoice.customer_id, 
invoice.shop_location,
sum(invoice.cost)
FROM invoice
GROUP BY
invoice.customer_name, invoice.customer_id, invoice.shop_location

如果不是invoice.shop_location值,那么可以对语句做些什么来识别哪些行与其他行相同?

2 个答案:

答案 0 :(得分:2)

试试这个 - 删除Invoice.ShopLocation

SELECT  
invoice.customer_name,  
invoice.customer_id,  
sum(invoice.cost) 
FROM invoice 
GROUP BY 
invoice.customer_name, invoice.customer_id

这将为您提供与其余字段匹配的所有行

答案 1 :(得分:1)

Select customer_name, Customer_id, count(Shop_location) from
(
    SELECT  
        invoice.customer_name,  
        invoice.customer_id,  
        invoice.shop_location, 
        sum(invoice.cost) 
    FROM invoice 
    GROUP BY 
        invoice.customer_name, 
        invoice.customer_id,
        invoice.shop_location 
 )
 Group by customer_name, Customer_id
 Having    count(Shop_location) > 1

上述查询将为您提供具有多个商店位置的客户名称和ID的组合

注意:我不确定这是否已经过优化