0

我需要在 SELECT 中显示值 MIN(pa.DataAdjudicacao)。以及如何替换此子查询以进行联接?我该怎么做?据我搜索,我还没有找到任何方法来做到这一点。请帮忙。

SELECT p.id, p.referencia
FROM PCTSproposta p
WHERE p.ID in (SELECT pa.Proposta
            FROM PropostaAdjudicada pa
            WHERE pa.Proposta = p.ID
            GROUP BY pa.Proposta
            HAVING MIN(pa.DataAdjudicacao) >= '2020-10-01' And MIN(pa.DataAdjudicacao) <= '2020-10-31')
4

2 回答 2

1

您的查询过于复杂。您使用子查询按IN谓词过滤数据,但选择ID您传递给子查询过滤器的相同内容。所以你的IN样子EXISTS。但是如果你需要那个分钟,你应该使用JOIN

SELECT p.id,
  p.referencia,
  pa2.DataAdjudicacao
FROM PCTSproposta p
  JOIN (
    SELECT pa.Proposta,
      MIN(pa.DataAdjudicacao) as DataAdjudicacao
    FROM PropostaAdjudicada pa
    GROUP BY pa.Proposta
    HAVING MIN(pa.DataAdjudicacao) BETWEEN date '2020-10-01'AND date '2020-10-31'
  ) pa2
    on pa2.Proposta = p.ID

根据Id列的角色(如果它是 的主键PCTSproposta)、数据完整性和基数,子查询可以合并到主查询中:

SELECT p.id,
  p.referencia,
  MIN(pa.DataAdjudicacao) as DataAdjudicacao
FROM PCTSproposta p
  JOIN PropostaAdjudicada pa
    on pa2.Proposta = p.ID
GROUP BY p.id,
  p.referencia
HAVING MIN(pa.DataAdjudicacao) BETWEEN date '2020-10-01'AND date '2020-10-31'
于 2020-11-10T09:58:49.267 回答
0

想到横向连接:

SELECT p.id, p.referencia, pa.*
FROM PCTSproposta p
CROSS APPLY (
    SELECT MIN(pa.DataAdjudicacao) minDataAdjudicacao
    FROM PropostaAdjudicada pa
    WHERE pa.Proposta = p.ID
) pa
WHERE pa.minDataAdjudicacao >= '20201001' AND pa.minDataAdjudicacao < '20201101'
于 2020-11-10T09:53:32.870 回答