WHERE子句,除非它位于HAVING子句或选择列表中包含的子查询中

时间:2013-12-14 10:04:14

标签: sql sql-server

我正在尝试执行以下查询。我面临上述错误。

聚合可能不会出现在WHERE子句中,除非它位于HAVING子句或选择列表中包含的子查询中,并且要聚合的列是外部引用。

SELECT student_id, 
       class_id, 
       item_id, 
       (SELECT stock 
        FROM   dbo.daily_closing_stock_details 
        WHERE  stock_reporting_date = Min(stock_reporting_date) 
               AND item_id = dcs.non_mrp_item_id) AS Stock 
FROM   dbo.daily_closing_stock_details 
GROUP  BY student_id, 
          sap_customer_id, 
          item_id 

5 个答案:

答案 0 :(得分:0)

您的子查询必须只返回一行和一列,然后聚合该值。请参阅更改

SELECT student_id, 
       class_id, 
       item_id, 
       sum((SELECT sum(stock) stock
        FROM   dbo.daily_closing_stock_details 
        WHERE  stock_reporting_date = stock_reporting_date 
               AND item_id = dcs.non_mrp_item_id)) AS Stock 
FROM   dbo.daily_closing_stock_details 
GROUP  BY student_id, 
          sap_customer_id, 
          item_id 

答案 1 :(得分:0)

您无法在WHERE子句中使用聚合函数过滤结果,为了更加一致,您需要使用HAVING子查询中的虚拟列应该为此放置TOP 1

返回一个结果
SELECT student_id, 
       class_id, 
       item_id, 
       (SELECT TOP 1 stock 
        FROM   dbo.daily_closing_stock_details 
        HAVING stock_reporting_date = Min(stock_reporting_date) 
               AND item_id = dcs.non_mrp_item_id) AS Stock 
FROM   dbo.daily_closing_stock_details 
GROUP  BY student_id, 
          sap_customer_id, 
          item_id 

答案 2 :(得分:0)

试试这个:

SELECT student_id, 
   class_id, 
   item_id,
   (SELECT stock 
    FROM   dbo.daily_closing_stock_details dcs
    WHERE item_id = dcs.non_mrp_item_id 
    HAVING stock_reporting_date = Min(stock_reporting_date)) as Stock 
FROM   dbo.daily_closing_stock_details 
GROUP  BY student_id, 
      sap_customer_id, 
      item_id 

答案 3 :(得分:0)

您必须使用别名,否则SQL Server会假定stock_reporting_date列是子查询表(在这种情况下为y)的一部分:

SELECT x.student_id, 
       x.class_id, 
       x.item_id, 
       (SELECT y.stock 
        FROM   dbo.daily_closing_stock_details y
        WHERE  y.stock_reporting_date = Min(x.stock_reporting_date) 
               AND y.item_id = x.item_id) AS Stock 
        -- I used x.item_id column instead of non_mrp_item_id
        -- If you have to use x.non_mrp_item_id instead of x.item_id then you need to replace this column within GROUP BY clause 
FROM   dbo.daily_closing_stock_details x
GROUP  BY x.student_id, 
          x.sap_customer_id, 
          x.item_id 

此外,在这种情况下,您需要在item_id和stock_reporting_date列上使用UNIQUE索引,否则您需要在子查询中使用聚合函数(MIN,MAX等:(SELECT MAX(y.stock) ...)或TOP((SELECT TOP(1) y.stock ... ORDER BY ...)

答案 4 :(得分:0)

不知道为什么你使用group by.you可以在我的查询中删除。也在你的查询中

AND item_id = dcs.non_mrp_item_id

不清楚,你可以加入它。只是让它发挥作用。

Select student_id, 
   class_id, 
   item_id,
    stock 
FROM   dbo.daily_closing_stock_details 
WHERE  stock_reporting_date =(select  Min(stock_reporting_date) FROM   dbo.daily_closing_stock_details GROUP  BY student_id, 
          sap_customer_id, 
          item_id  )