如何向此查询添加更多

时间:2018-08-30 16:25:48

标签: sql

我在下面编写了查询,以获取特定帐户代码(如果存在)的每日费用。但是,我需要添加另一个帐户代码,但是我只希望包含在与其他帐户代码相同的日期中。我不太确定如何做到这一点。我无法将其添加到WHERE中,因为无论此新帐户代码是否存在,我仍然希望它带回其他费用。我目前正在尝试子查询

SELECT Distinct
  DailyCosts.WellID, DailyCosts.JobID,CasingInfo.HoleSection,
  CasingInfo.ShoeDepth, 
  SUM(DailyCosts.DailyCost) OVER(Partition by DailyCosts.WellID 
    Order by DailyCosts.WellID) As SurfaceCosts
FROM DailyCosts 
JOIN CasingInfo ON DailyCosts.WellID = CasingInfo.WellID
WHERE (AccountCode ='10670' 
    OR AccountCode ='10680'
    OR AccountCode = '10202'
    OR AccountCode = '10203') 
  AND (DailyCost <> .0001 
  AND DailyCost <> 0.001 
  AND DailyCost <> 0.00 
  AND DailyCost <> .002 
  AND DailyCost <> 0.01 
  AND DailyCost <> 1) 
  AND (HoleSection = 'surf') 
ORDER BY WellID, SurfaceCosts

1 个答案:

答案 0 :(得分:0)

因此,您在问题中遗漏了很多信息,但这是一些使您入门的信息。

首先,我建议您设置查询的格式,以使其更具可读性。

Select Distinct
    DailyCosts.WellID, 
    DailyCosts.JobID,
    CasingInfo.HoleSection,
    CasingInfo.ShoeDepth, 
    SUM(DailyCosts.DailyCost) 
    OVER (Partition by DailyCosts.WellID Order by DailyCosts.WellID) As SurfaceCosts
From DailyCosts 
    JOIN CasingInfo 
        ON DailyCosts.WellID = CasingInfo.WellID
Where   
    AccountCode IN('10670' , '10680' , '10202' , '10203') AND 
    DailyCost NOT IN (0.0001 , 0.001 , 0.00 ,0.002 , 0.01 , 1) AND 
    HoleSection = 'surf' 
Order by WellID, SurfaceCosts

第二,请注意,用IN子句(更短更漂亮)替换了Multi-OR / Multi-AND逻辑。

最后->“仅在与其他帐户代码显示在同一日期时,我才希望包含它” 您没有在示例中提供对日期的任何引用(无列/无模式),但假设其在连接的表之一中 您应该能够使用WHERE条款中的其他条件对此进行过滤,请尝试在表达式为 像这样:

AND case when AccountCode = '<the additional account code>' and <date date_column> in (select <date_column> from table where AccountCode in (<existing accounts>))...