T-SQL"不包含在聚合函数或GROUP BY子句中#34;

时间:2015-06-24 15:47:21

标签: sql-server tsql subquery aggregate

我有一个工作查询,告诉我最接近美国每个邮政编码的商店位置,但当我尝试让外部查询选择所述商店的相关邮政编码时,它告诉我必须添加ZipCode为聚合;但是,如果我通过Zip订购,那么它并没有向我展示所有的笛卡尔产品。任何帮助表示赞赏。

select
Sub1.Zip as Zip,
Sub1.Zip_ID as Zip_ID,
MIN(Sub1.Distance) as Distance from
    (
    SELECT 
    Z.Zip,
    Z.Zip_ID, 
       ((Sqrt(Square((Z.lat  - S.lat) *68.96799738887665) 
         + Square((Z.long - S.long)*54.69366983621222)))) Distance
    FROM   
    Tbl_Stores_Coordinates S
    CROSS JOIN Zip_Code_Coordinates Z
    )Sub1
group by Sub1.Zip_ID

1 个答案:

答案 0 :(得分:5)

您收到此错误的原因是SELECT ZipZip_ID GROUPZip_ID只是GROUP

SELECT的所有非汇总列都必须select Sub1.Zip as Zip, Sub1.Zip_ID as Zip_ID, MIN(Sub1.Distance) as Distance .... group by Sub1.Zip, Sub1.Zip_ID ,因此:

-doSomethingWithImage