在主查询中使用子查询结果

时间:2019-02-21 13:36:12

标签: sql sql-server subquery

如何使子查询结果在主查询中可用,例如此示例?

awk -v keyname="$somestring" '$0 ~ "^ *# *" keyname " +([0-9]([0-9]([0-9]([0-9][0-9]?)?)?)?|[A-Za-z]+)($|[ \t])"'

3 个答案:

答案 0 :(得分:1)

一种选择是将当前查询放入CTE中,然后使用别名对它进行子查询:

WITH cte AS (
    SELECT Id AS ParticipantId, TeamId,
        ISNULL((SELECT TOP(1) Weight FROM ParticipantData WHERE (ParticipantId = Participants.Id) AND (Weight <> 0) ORDER BY Date), 0) AS FirstWeight,
        ISNULL((SELECT TOP(1) Weight FROM ParticipantData WHERE (ParticipantId = Participants.Id) AND (Weight <> 0) ORDER BY Date DESC), 0) AS LastWeight
    FROM Participants
)

SELECT
    ParticipantId,
    TeamId,
    FirstWeight,
    LastWeight,
    FirstWeight - LastWeight As WeightDiff
FROM cte;

答案 1 :(得分:0)

Alias行中的FirstWeight,LastWeight无法使用SQL Server,您可以通过以下方式更改查询

SELECT Id AS ParticipantId, TeamId,
ISNULL((SELECT TOP(1) Weight FROM ParticipantData WHERE (ParticipantId = Participants.Id) AND (Weight <> 0) ORDER BY Date), 0) AS FirstWeight,
ISNULL((SELECT TOP(1) Weight FROM ParticipantData WHERE (ParticipantId = Participants.Id) AND (Weight <> 0) ORDER BY Date DESC), 0) AS LastWeight,
ISNULL((SELECT TOP(1) Weight FROM ParticipantData WHERE (ParticipantId = Participants.Id) AND (Weight <> 0) ORDER BY Date), 0)- ISNULL((SELECT TOP(1) Weight FROM ParticipantData WHERE (ParticipantId = Participants.Id) AND (Weight <> 0) ORDER BY Date DESC), 0) As WeightDiff // this doesn't work
FROM Participants

或者您可以使用子查询进入下一级

select ParticipantId, TeamId,FirstWeight,LastWeight,
 FirstWeight-LastWeight as WeightDiff from
  ( 
  SELECT Id AS ParticipantId, TeamId,
    ISNULL((SELECT TOP(1) Weight FROM ParticipantData WHERE (ParticipantId = Participants.Id) AND (Weight <> 0) ORDER BY Date), 0) AS FirstWeight,
    ISNULL((SELECT TOP(1) Weight FROM ParticipantData WHERE (ParticipantId = Participants.Id) AND (Weight <> 0) ORDER BY Date DESC), 0) AS LastWeight
FROM Participants
  ) as t

答案 2 :(得分:0)

使用outer apply

SELECT Id AS ParticipantId, TeamId,
       COALESCE(f.FirstWeight, 0) as FirstWeight,
       COALESCE(f.LastWeight, 0) as LastWeight,
       (f.FirstWeight - l.LastWeight) As WeightDiff 
FROM Participants p OUTER APPLY
     (SELECT TOP(1) pd.Weight as firstWeight
      FROM ParticipantData pd
      WHERE (pd.ParticipantId = p.Id) AND Weight <> 0
      ORDER BY Date
     ) f OUTER APPLY
     (SELECT TOP(1) pd.Weight as lastWeight
      FROM ParticipantData pd
      WHERE (pd.ParticipantId = p.Id) AND Weight <> 0
      ORDER BY Date DESC
     ) l;