【问题标题】:Group query results by location, client name and month按位置、客户名称和月份对查询结果进行分组
【发布时间】:2015-07-07 21:57:45
【问题描述】:

我有以下表格:

location_location
----------------
id       
name     
email             

sales_sale
---------
id
date
total_amount
location_id
client_id

client_client
-------------
id 
name

我想创建一个查询,给出销售列的总和,并按月份、位置和客户名称对结果进行分组,如下所示:

Desired Result:
Location name  /  month /  sum(total_amount) / client_name
San Francisco      Jan        250                CISCO

我的尝试:

select name(select name from location_location),
to_char(date,'Mon') as mon,
sum("total_amount") as "total_amount",
client_amount    
from sales_sale
group by 1,3
order by mon desc

INNER JOIN name ON client_client.id =sales_sale.client_id and 
INNER JOIN location ON location_location.id =sales_sale.location_id;

【问题讨论】:

    标签: sql postgresql select group-by


    【解决方案1】:

    您的想法是正确的,尽管您的语法略有偏差:

    SELECT   l.name, 
             TO_CHAR(date, 'MON')
             client_name,
             SUM(total_amount)
    FROM     location_location l
    JOIN     sales_sale s ON s.location_id = l.id
    JOIN     client_client c ON s.client_id = c.id
    GROUP BY l.name, 
             TO_CHAR(date, 'MON')
             client_name
    

    【讨论】:

      猜你喜欢
      • 2013-07-03
      • 1970-01-01
      • 1970-01-01
      • 2020-06-27
      • 1970-01-01
      • 1970-01-01
      • 2018-08-26
      • 1970-01-01
      • 2019-03-09
      相关资源
      最近更新 更多