按地理(或几何)分组的聚合/计数行
Posted
技术标签:
【中文标题】按地理(或几何)分组的聚合/计数行【英文标题】:aggregate / count rows grouped by geography (or geometry) 【发布时间】:2017-06-06 01:47:57 【问题描述】:我有一张桌子,例如:
Create Table SalesTable
( StuffID int identity not null,
County geography not null,
SaleAmount decimal(12,8) not null,
SaleTime datetime not null )
它记录了每次销售的金额、时间和销售所在县的地理位置。
我想运行这样的查询:
Select sum(SaleAmount), County from SalesTable group by County
但如果我尝试这样做,我会得到:
The type "geography" is not comparable. It cannot be used in the GROUP BY clause.
但我想知道每个县的销售量。烦人的是,如果我将县缩写(SDC、LAC、SIC 等),那么我可以将它们分组,因为它只是一个 varchar。但后来我出于其他原因使用了 geography 数据类型。
【问题讨论】:
【参考方案1】:有一个函数可以将地理类型用作字符
试试这个
Select sum(SaleAmount), County.STAsText() from SalesTable
group by County.STAsText()
【讨论】:
【参考方案2】:我会提出一个稍微不同的结构:
create table dbo.County (
CountyID int identity not null
constraint [PK_County] primary key clustered (CountyID),
Name varchar(200) not null,
Abbreviation varchar(10) not null,
geo geography not null
);
Create Table SalesTable
(
StuffID int identity not null,
CountyID int not null
constraint FK_Sales_County foreign key (CountyID)
references dbo.County (CountyID),
SaleAmount decimal(12,8) not null,
SaleTime datetime not null
);
从那里,您的聚合看起来像:
Select c.Abbreviation, sum(SaleAmount)
from SalesTable as s
join dbo.County as c
on s.CountyID = c.CountyID
group by c.Abbreviation;
如果您确实需要聚合中的地理列,那么您是一个子查询或一个公用表表达式:
with s as (
Select c.CountyID, c.Abbreviation,
sum(s.SaleAmount) as [TotalSalesAmount]
from SalesTable as s
join dbo.County as c
on s.CountyID = c.CountyID
group by c.Abbreviation
)
select s.Abbreviation, s.geo, s.TotalSalesAmount
from s
join dbo.County as c
on s.CountyID = s.CountyID;
【讨论】:
以上是关于按地理(或几何)分组的聚合/计数行的主要内容,如果未能解决你的问题,请参考以下文章
MongoDB聚合使用表达式运算符(函数)分组按条件计数统计案例一则