【问题标题】:Show a Total for a SQL Table显示 SQL 表的总计
【发布时间】:2017-02-14 17:06:59
【问题描述】:

我试图在这个 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

【问题讨论】:

  • I am oblivious on why the result shows ones redundantly for the same Builders and Lot Size combinations even though I have grouped by ALL the columns in the script. -- 可能是因为sd.Address ?
  • 是的,需要删除sd.Address

标签: sql postgresql


【解决方案1】:

您的group bydm.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"

【讨论】:

  • @Pythoner - 您可以通过"Builder" 订购。在我的答案中更新。
【解决方案2】:

试试这个:

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) &gt; 0

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2020-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-24
      • 2018-11-23
      • 1970-01-01
      • 2020-02-15
      • 2018-03-31
      相关资源
      最近更新 更多