2017-06-06 147 views
0

我有一個表,如:彙總/計數行

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。但由於其他原因,我使用了地理數據類型。

回答

0

有一個功能與地理類型爲char工作

試試這個

Select sum(SaleAmount), County.STAsText() from SalesTable 
group by County.STAsText() 
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;