代码之家  ›  专栏  ›  技术社区  ›  MKF

如何子查询-需要根据计算列计算新值

sql
  •  0
  • MKF  · 技术社区  · 7 年前

    第一个查询应该计算记录数-第二个查询需要平均计算记录数我不知道如何正确使用子查询这就是我所拥有的,显然,“鸟”列不存在,因为它是在子查询中创建的,因此我的外部查询不起作用:

    SELECT
          avg(birds)
        FROM [FocalAreas].[dbo].[Observation] as o, FocalAreas.dbo.Count as c, FocalAreas.dbo.MonitoringPoint as mp
        WHERE EXISTS
          (Select 
              Count(o.ObservationID) as birds
              ,o.CountID
              ,mp.MonitoringPointID
                  FROM [FocalAreas].[dbo].[Observation] as o, FocalAreas.dbo.Count as c, FocalAreas.dbo.MonitoringPoint as mp
                  where o.CountID = c.CountID
                  and c.MonitoringPointID = mp.MonitoringPointID
                  and StateID = 'NE'
                  and AOUSpeciesID = 1
                  and Route = 'Focal'
                  and datepart(year, CountDate) = 2014
                  group by o.CountID, mp.MonitoringPointID)
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Carsten Massmann    7 年前

    我只能猜测,因为你的问题需要更详细的描述,但也许你想做以下几点:

    SELECT
      avg(birds)
    FROM (Select 
          Count(o.ObservationID) as birds
          ,o.CountID
          ,mp.MonitoringPointID
          FROM [FocalAreas].[dbo].[Observation] as o, FocalAreas.dbo.Count as c, FocalAreas.dbo.MonitoringPoint as mp
          where o.CountID = c.CountID
              and c.MonitoringPointID = mp.MonitoringPointID
              and StateID = 'NE'
              and AOUSpeciesID = 1
              and Route = 'Focal'
              and datepart(year, CountDate) = 2014
          group by o.CountID, mp.MonitoringPointID) as subq