GROUP BY的替代方法

时间:2019-06-28 18:50:12

标签: sql-server

我正在寻找一种替代方法,用于删除别名列的重复项。我知道我不能在别名上使用GROUP BY函数,但是我不知道如何清除该列中的重复项。

SELECT        
(select Sites.SiteZipCode 
FROM Sites 
WHERE Sites.SiteName = TransportationPolicies.DestinationSite) AS DESTZIP1,
(SELECT        Sites.SiteZipCode
FROM Sites 
WHERE Sites.SiteName = TransportationPolicies.SOURCESite) AS SOURCESITE1,
((select Sites.SiteZipCode FROM Sites WHERE Sites.SiteName = TransportationPolicies.DestinationSite) + '_' + (SELECT  Sites.SiteZipCode FROM Sites WHERE Sites.SiteName = TransportationPolicies.SOURCESite)) 
AS CONCZIP, TransportationPolicies.SourceSite, TransportationPolicies.DestinationSite
FROM TransportationPolicies
GROUP BY CONCZIP

2 个答案:

答案 0 :(得分:0)

很少需要内联子查询。您只需要两次联接到Sites即可检索所需的列。除了Smor对格式的观察之外,表别名也将大大简化代码的复杂性。

这是未经测试的,因为我们没有可用的数据,但是我相信应该返回您想要的结果。根据您的数据,您可能需要使用LEFT JOIN

SELECT DISTINCT
  dest.SiteZipCode AS DESTZIP1,
  src.SiteZipCode AS SOURCESITE1,
  dest.SiteZipCode + '_' + src.SiteZipCode AS CONCZIP, 
  tpol.SourceSite, 
  tpol.DestinationSite
FROM 
  TransportationPolicies AS tpol
JOIN
  Sites as dest
    ON dest.SiteName = tpol.DestinationSite
JOIN
  Sites as src
    ON src.SiteName = tpol.SOURCESite;

答案 1 :(得分:-1)

不是答案-只是说明格式化/空格如何增加阅读和理解查询的能力

SELECT        
   (select Sites.SiteZipCode FROM Sites 
    WHERE Sites.SiteName = TransportationPolicies.DestinationSite) AS DESTZIP1,

   (SELECT Sites.SiteZipCode FROM Sites 
    WHERE Sites.SiteName = TransportationPolicies.SOURCESite) AS SOURCESITE1,

   ((select Sites.SiteZipCode FROM Sites WHERE Sites.SiteName = TransportationPolicies.DestinationSite) 
   + '_' 
   + (SELECT  Sites.SiteZipCode FROM Sites WHERE Sites.SiteName = TransportationPolicies.SOURCESite)) 
   AS CONCZIP, 

   TransportationPolicies.SourceSite, 
   TransportationPolicies.DestinationSite
FROM TransportationPolicies
GROUP BY CONCZIP
ORDER BY CONCZIP;