代码之家  ›  专栏  ›  技术社区  ›  CJ7

SQL:如何从group by语句中获取更多信息

  •  0
  • CJ7  · 技术社区  · 14 年前

    考虑以下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 回复  |  直到 14 年前
        1
  •  2
  •   Sachin Shanbhag    14 年前

    尝试此操作-删除invoice.shoplocation

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

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

        2
  •  1
  •   The King    14 年前
    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的组合

    注:我不确定这是否是优化的