我有一张表如:
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数据类型。
答案 0 :(得分:1)
我建议采用略有不同的结构:
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;
答案 1 :(得分:0)
有一个函数可以使用地理类型作为char
试试这个
Select sum(SaleAmount), County.STAsText() from SalesTable
group by County.STAsText()