具有多个表的分组

时间:2012-09-14 17:55:36

标签: sql sql-server

我相信Group By会解决以下问题,但也许它会选择Distinct。不管怎样,我恭敬地求助于你:

目标:

按协议合并,然后是LaborCode,然后是Schedule。我为一家执行多项服务的公司工作,我想采取任何日期,并指定我们每周服务的每周工作日期。在一个月的时间里,我们将有(4)星期一 - 我想看到一个星期一。作为旁注,我尝试过XML Path,但似乎没有用。

守则:

Select Top 100 Percent Agreements.AgrmntID, JobSites.SiteName,
  Customers.CompanyName, LaborCodeTypes.Description As LaborCode, DateName(dw,
  AgreementSchedules.SchedDate) as Schedule
From Agreements Inner Join
  AgreementSchedules On Agreements.AgrmntID = AgreementSchedules.AgrmntID
  Inner Join
  Customers On Agreements.CustID = Customers.CustID Inner Join
  JobSites On Agreements.CustSiteID = JobSites.CustSiteID Left Outer Join
  LaborCodeTypes On AgreementSchedules.RepairID = LaborCodeTypes.RepairID
Where Agreements.Status = 2

数据(附表来自AgreementSchedules.SchedDate) - 选择了2周:

AgrmntID    SiteName   Company   LaborCode    Schedule
---------- ---------- ---------- ---------- ----------
1           JOB01      COMP01    Sweeping     Monday
1           JOB01      COMP01    Sweeping     Wednesday
1           JOB01      COMP01    Sweeping     Monday
1           JOB01      COMP01    Sweeping     Wednesday
1           JOB01      COMP01    Porter       Thursday
1           JOB01      COMP01    Porter       Thursday
2           JOB02      COMP02    Landscaping  Tuesday
2           JOB02      COMP02    Landscaping  Tuesday

期望的输出:

AgrmntID    SiteName   Company   LaborCode    Schedule
---------- ---------- ---------- ---------- ----------
1           JOB01      COMP01    Sweeping     Monday
1           JOB01      COMP01    Sweeping     Wednesday
1           JOB01      COMP01    Porter       Thursday
2           JOB02      COMP02    Landscaping  Tuesday

非常感谢你。我一直在试图解决这个问题几天没有运气。

2 个答案:

答案 0 :(得分:1)

一个独特的应该在这里工作得很好..

FYI Group byDistinct基本上彼此相同(实际上这是一些数据库实现DISTINCT的方式)。

注意,Distinct更快,因为它没有对结果进行排序

此外,使用Distinct更清晰,更易于阅读和维护。您的代码的其他读者将立即获得意图..

答案 1 :(得分:0)

要么工作。

我会选择DISTINCT

Select DISTINCT Agreements.AgrmntID, JobSites.SiteName, 
  Customers.CompanyName, LaborCodeTypes......