我有以下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
并返回错误
" Singleton Select中的多行"。
这是数据库的样本
任何提示都将深受赞赏
由于
答案 0 :(得分:0)
问题出在CTE
SELECT
子查询中。
我认为您可以使用CASE
express代替SELECT
Subquery
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
OR
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'
我不知道你期望的结果是什么。所以我猜这两个问题对你有帮助。
答案 1 :(得分:0)
您的查询想要检索匹配GUIA
的一个,但似乎NUM_REFE
每个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;