当未使用EXISTS引入子查询时,只能在选择列表中指定一个表达式

时间:2011-06-28 21:38:30

标签: sql-server tsql

我发布了谷歌和stackoverflow之前发布了这个。这个案子有很多帖子,但我在查询中找不到问题。

    DECLARE @hipero_a int
SET @hipero_a = 1

SELECT
CASE @hipero_a 
WHEN 1 THEN --month
    (
    SELECT Year(o.AccomplishDate) AS [Rok], Month(o.AccomplishDate) AS [Miesiąc], SUM(oi.Price) AS [Przychód]
    FROM Orders o JOIN OrdersItems oi ON oi.OrderId = o.Id
    WHERE o.State = 0
    GROUP BY Year(o.AccomplishDate), Month(o.AccomplishDate)
    --ORDER BY Year(o.AccomplishDate), Month(o.AccomplishDate) ASC
)
WHEN 2 THEN --year
    (
    SELECT Year(o.AccomplishDate) AS [Rok], SUM(oi.Price) AS [Przychód]
    FROM Orders o JOIN OrdersItems oi ON oi.OrderId = o.Id
    WHERE o.State = 0
    GROUP BY Year(o.AccomplishDate)
    --ORDER BY Year(o.AccomplishDate) ASC
    )
    END

我收到错误:

  

Msg 116,Level 16,State 1,Line 14   只能指定一个表达式   在子查询中的选择列表中   没有与EXISTS一起介绍。

     

消息   116,16级,1号,22号线   一个表达式可以在。中指定   子查询不是时选择列表   与EXISTS一起介绍。

有什么问题?

3 个答案:

答案 0 :(得分:2)

你想使用IF代替CASE

DECLARE @hipero_a int
SET @hipero_a = 1

IF @hipero_a = 1 BEGIN ;
    SELECT Year(o.AccomplishDate) AS [Rok], Month(o.AccomplishDate) AS [Miesiąc], SUM(oi.Price) AS [Przychód]
    FROM Orders o JOIN OrdersItems oi ON oi.OrderId = o.Id
    WHERE o.State = 0
    GROUP BY Year(o.AccomplishDate), Month(o.AccomplishDate)
    --ORDER BY Year(o.AccomplishDate), Month(o.AccomplishDate) ASC
END ;
IF @hipero_a = 2 BEGIN ;
    SELECT Year(o.AccomplishDate) AS [Rok], SUM(oi.Price) AS [Przychód]
    FROM Orders o JOIN OrdersItems oi ON oi.OrderId = o.Id
    WHERE o.State = 0
    GROUP BY Year(o.AccomplishDate)
    --ORDER BY Year(o.AccomplishDate) ASC
    )
END;

答案 1 :(得分:1)

AlexKuznetsov有正确的答案。问题是外部选择期望可以返回的列列表。 Case语句是其中一列,因此subselect必须返回最多一列才能作为列值传递给父选择。

希望这有助于解释为什么你会看到你得到的错误。

史蒂夫G。

答案 2 :(得分:0)

谢谢!我只是厌倦了找到这个。所以这有效:

DECLARE @DivideBy int
SET @DivideBy = 1

IF @DivideBy = 1 BEGIN ;
    SELECT Year(o.AccomplishDate) AS [Rok], Month(o.AccomplishDate) AS [Miesiąc], SUM(oi.Price) AS [Przychód]
    FROM Orders o JOIN OrdersItems oi ON oi.OrderId = o.Id
    WHERE o.State = 0
    GROUP BY Year(o.AccomplishDate), Month(o.AccomplishDate)
    ORDER BY Year(o.AccomplishDate) DESC, Month(o.AccomplishDate) DESC
END ;
IF @DivideBy = 2 BEGIN ;
    SELECT Year(o.AccomplishDate) AS [Rok], SUM(oi.Price) AS [Przychód]
    FROM Orders o JOIN OrdersItems oi ON oi.OrderId = o.Id
    WHERE o.State = 0
    GROUP BY Year(o.AccomplishDate)
    ORDER BY Year(o.AccomplishDate) DESC
END;

我可以以某种方式优化它吗?