显示SQL表的总计

时间:2017-02-14 17:06:59

标签: sql postgresql

我试图在这个sql语法的底部添加一个Total行,但到目前为止还没有收到任何突破。我已经看过以下但是他们两个都不符合我的条件。有人可以就此提供帮助。

Add a summary row with totals

Adding a total row to the end of query result

select dm.Builder ||' ('|| dm.Lot_Size || '''s)' as"Builder",count(sd.Address) "The Count",
dm."Construction_ID"
from input dm
left join data sd on sd.inputfk = dm.inputpk
and sd.Closing Date >= DATE '01/01/2017' and sd.Closing Date < DATE '06/30/2017'
where dm.Construction_ID = 'AJR'
group by dm.Builder,dm.Lot_Size, dm.Project_ID
having count(sd.Address) > 0
order by dm.Builder

当我运行它时:

  Builder            The Count     Construction_ID 
Jake's Homes (55's)     2               AJR
Jake's Homes (65's)     3               AJR
Maggie's Homes (65's)   5               AJR
Maggie's Homes (66's)   2               AJR
Maggie's Homes (75's)   3               AJR
Maggie's Homes (90's)   1               AJR

 Total ---------->     16

3 个答案:

答案 0 :(得分:2)

group by dm.Project_ID, sd.Address可能导致{。}}。

总计,您可以使用ROLLUP

试试这个:

select coalesce(dm.Builder || ' (' || dm.Lot_Size || '''s)', 'Total') as "Builder",
    count(sd.Address) "The Count",
    dm."Construction_ID"
from input dm
left join data sd on sd.inputfk = dm.inputpk
    and sd.Closing date >= date '01/01/2017'
    and sd.Closing date < date '06/30/2017'
where dm.Construction_ID = 'AJR'
group by rollup(dm.Builder || ' (' || dm.Lot_Size || '''s)')
having count(sd.Address) > 0
order by "Builder"

答案 1 :(得分:1)

试试这个:

select dm.Builder ||' ('|| dm.Lot_Size || '''s)' as"Builder",count(sd.Address) "The Count",
dm."Construction_ID"
from input dm
left join data sd on sd.inputfk = dm.inputpk
and sd.Closing Date >= DATE '01/01/2017' and sd.Closing Date < DATE '06/30/2017'
where dm.Construction_ID = 'AJR'
group by rollup( (dm.Builder,dm.Lot_Size, dm.Project_ID) )
having count(sd.Address) > 0
order by dm.Builder

只是......为什么你需要count(sd.Address) > 0

答案 2 :(得分:0)

鉴于帖子是用postgresql标记的,假设它是针对该平台的;因此,请参阅https://www.postgresql.org/docs/9.5/static/queries-table-expressions.html#QUERIES-GROUPING-SETS