2

我很陌生SQL,我一生都无法弄清楚为什么我不能做我在这里尝试的事情。我正在尝试在一次旅行中获得最少数量的免费座位,并按包裹 ID 对它们进行分组。

第一个子查询有效,但第二个是我无法弄清楚的。它说

'where 子句' 中的未知列 SuperPaket

select Paket.PaketID as "SuperPaket", Beskrivning, Resa.AvgångStad, Resa.AvgångTid, Resa.AvgångDatum,

    (select AnkomstTid from Resa where Resa.ResID in 
        (select ResID from PaketResa where PaketResa.PaketID = SuperPaket and Ordningsnr =
            (select max(Ordningsnr) from PaketResa where PaketResa.PaketID = SuperPaket))) "AnkomstTid",

        (select min(LedigaPlatser) from
            (select sum(AntalPlatser - Count) "LedigaPlatser", ResID from(
                select Bokning.ResID, AntalPlatser, sum(Bokning.AntalBiljetter) as Count from 
                    (Resa inner join Bokning on Resa.ResID = Bokning.ResID) where Bokning.ResID in
                        (select PaketResa.ResID from PaketResa where PaketResa.PaketID = SuperPaket)
                group by Bokning.ResID order by Count desc)
            as CountTable group by ResID) 
        as T) "LedigaPlatser"

    from ((Paket inner join PaketResa on Paket.PaketID = PaketResa.PaketID) inner join Resa on PaketResa.ResID = Resa.ResID) group by Paket.PaketID;

为什么这对第一个子查询有效,而对第二个子查询无效?


更新.. 当我在 from 子句中放置“子子查询”时,似乎出现了错误。我不知道如何重写有问题的查询来解决这个问题,我真的很感激一些帮助。谢谢..

4

2 回答 2

2

我认为您不能在and的子句中使用列别名wheremysqloracle

来自 mysql 文档

标准 SQL 不允许在 WHERE 子句中引用列别名。施加此限制是因为在评估 WHERE 子句时,可能尚未确定列值。

您可以在 GROUP BY、ORDER BY 或 HAVING 子句中使用别名来引用列:

我不知道sql server

补充: 您的子查询可能没有得到Paket.PaketId。尝试from通过添加修改大多数外部查询的子句

(select Paket.PaketID as "SuperPaket" from Paket)

如下

from (
      (Paket inner join PaketResa on Paket.PaketID = PaketResa.PaketID)   
inner join Resa on PaketResa.ResID = Resa.ResID),
      (select Paket.PaketID as "SuperPaket" from Paket)
group by Paket.PaketID;

也从第一个删除别名,select然后说select SuperPaket

于 2012-10-19T11:29:46.910 回答
-1

您的专栏是 Paket.PaketID 而不是“SuperPaket”,所以无论您使用 superpaket 的地方都使用 Paket.PaketID

select Paket.PaketID as "SuperPaket", Beskrivning, Resa.AvgångStad, 
        Resa.AvgångTid, Resa.AvgångDatum,

(select AnkomstTid from Resa where Resa.ResID in 
    (select ResID from PaketResa where PaketResa.PaketID = Paket.PaketID and Ordningsnr =
        (select max(Ordningsnr) from PaketResa where PaketResa.PaketID = Paket.PaketID))) "AnkomstTid",

    (select min(LedigaPlatser) from
        (select sum(AntalPlatser - Count) "LedigaPlatser", ResID from(
            select Bokning.ResID, AntalPlatser, sum(Bokning.AntalBiljetter) as Count from 
                (Resa inner join Bokning on Resa.ResID = Bokning.ResID) where Bokning.ResID in
                    (select PaketResa.ResID from PaketResa where PaketResa.PaketID = Paket.PaketID)
            group by Bokning.ResID order by Count desc)
        as CountTable group by ResID) 
    as T) "LedigaPlatser"

from ((Paket inner join PaketResa on Paket.PaketID = PaketResa.PaketID) inner join Resa on PaketResa.ResID = Resa.ResID) group by Paket.PaketID;
于 2012-10-19T08:39:17.447 回答