0

我有以下 SQL:

WITH G1 AS 
(SELECT G.NUM_REFE, G.GUIA AS MASTER, 
        (SELECT H.GUIA FROM SAAIO_GUIAS H WHERE G.NUM_REFE = H.NUM_REFE AND H.IDE_MH ="H" AND H.CONS_GUIA="1" ) AS HOUSE
FROM SAAIO_GUIAS G WHERE G.IDE_MH ="M" AND G.CONS_GUIA ="1" )
SELECT
*
FROM G1

它返回错误

“单例选择中的多行”。

这是数据库的示例

第一列是 NUM_REFE,第二列是 GUIA,第三列是 IDE_MH,第四列是 CONS_GUIA

任何提示将不胜感激

谢谢

4

2 回答 2

0

这个问题在CTE SELECT子查询中。

我认为您可以使用CASEexpress 而不是SELECTSubquery

WITH G1 AS 
(
select
  num_refe,
  Case when ide_mh = 'M' then GUIA ELSE '' END as MASTER,
  Case when ide_mh = 'H' then GUIA ELSE '' END as HOUSE
from saaio_guias
where cons_guia = 1 
)
SELECT
*
FROM G1

或者

SELECT G.NUM_REFE, G.GUIA AS MASTER,H.GUIA
FROM SAAIO_GUIAS G 
INNER JOIN 
(
    SELECT * 
    FROM SAAIO_GUIAS
    WHERE IDE_MH ='H'  AND CONS_GUIA='1'
) AS H ON  G.NUM_REFE = H.NUM_REFE
WHERE G.IDE_MH ='M' AND G.CONS_GUIA ='1'

我不知道您的期望结果是什么。所以我想这两个查询可能会对您有所帮助。

于 2018-03-28T15:05:20.417 回答
0

您的查询想要检索一个匹配GUIA项,但似乎每个NUM_REFEfor可以有多个条目IDE_MH = 'H' AND CONS_GUIA = 1。检查这个

select num_refe
from saaio_guias
where ide_mh = 'H'
  and cons_guia = 1
group by num_refe
having count(*) > 1;

这应该没有结果,但它可能会。如果确实如此,那么它对您的查询不起作用,您必须考虑在这种情况下选择哪个值。也许只是最小值或最大值:

(
  select min(h.guia)
  from saaio_guias h
  ...

或者,也许您想从表中删除您认为重复的行并添加约束(num_refe + ide_mh + cons_guia 上的唯一索引)以防止将来出现此类记录。

顺便说一句,您的查询可以使用条件聚合更简单地编写:

select
  num_refe,
  any_value(case when ide_mh = 'M' then guia end) as master,
  any_value(case when ide_mh = 'H' then guia end) as guia
from saaio_guias
where cons_guia = 1
group by num_refe
order by num_refe;
于 2018-03-28T15:06:17.730 回答