0

我有以下查询:

select
    fooditemid,
    sum(mealsize) as mealsize,
    mealdate
from Phase2FoodItems
where`
    userid = 190
    and mealdate between
        (select dietstartdate from Users where userid = 190)
        and GETDATE()
group by mealdate

我知道这基本上是要求 SQL 在没有提供足够信息的情况下向我提供数据(它不知道应该如何处理未在 group by 中指定的列,即 sum、average 等)。

不幸的是,将所有其余列添加到 group by 并没有给我我正在寻找的mealsize列的总和值。事实上,我得到的数据与没有 sum 和 group by 的数据完全相同。

我想我在这里遗漏了一个概念,任何人都可以解释和/或建议一个新的 sql 语句,它可以让我得到 mealdate 列中每个值的 mealize 列的总和吗?

4

4 回答 4

2

因为您使用的是Aggregate( SUM ) 函数,所以您需要在GROUP BY子句中指定所有其他列。

select
    fooditemid,
    sum(mealsize) as mealsize,
    mealdate
from Phase2FoodItems
where
    userid = 190
    and mealdate between
        (select dietstartdate from Users where userid = 190)
        and GETDATE()
group by mealdate, fooditemid
于 2013-06-05T08:42:24.113 回答
1

如果该列未出现在 group by 子句中(即在您的情况下),则 select 子句中不能有列fooditemid。如果要保留fooditemid列,而总和为mealsize,则可以在 a子查询。例如:

select
    outertable.fooditemid,
    outertable.mealdate,
    subquery.mealsize
from 
    Phase2FoodItems outertable
    inner join
    (
      select sum(inner.mealsize) mealsize
      from Phase2FoodItems inner
      where inner.userid = 190
        and inner.mealdate between
          (select dietstartdate from Users where userid = 190)
          and GETDATE() 
      group by inner.mealdate, inner.fooditemid
    ) subquery
    on subquery.fooditemid = outer.fooditemid
where
    outertable.userid = 190
    and outertable.mealdate between
        (select dietstartdate from Users where userid = 190)
        and GETDATE()
于 2013-06-05T08:55:15.663 回答
0

要分组的所有列都应该出现在您的 GROUP BY 子句中,以便 SQL Server 开始使用......其他 RDBMS 更宽容,并将返回非聚合列的第一个值而不是错误。

在您添加其他列的地方,您发现您的表达到了最精细的粒度级别 - 您需要准确计算出您需要的粒度级别并将这些列添加到您的 GROUP BY 和 SELECT 中,而不是引用其他列在您的选择中。

于 2013-06-05T08:44:09.017 回答
0

GROUP BY语句与聚合函数结合使用,将结果集按一列或多列分组...所以这将消除您的错误...

select
    fooditemid,
    sum(mealsize) as mealsize,
    mealdate
from Phase2FoodItems
where`
    userid = 190
    and mealdate between
        (select dietstartdate from Users where userid = 190)
        and GETDATE()
group by mealdate, fooditemid

但这将按两列(即用餐日期和 fooditemid

Select fooditemid, mealsize,
 mealdate from (
Select Row_Number() Over(Partition By Meal Date Order By fooditemid) as Row,
     fooditemid,
     sum(mealsize) as mealsize,
     mealdate
    from Phase2FoodItems
     where`
     userid = 190
     and mealdate between
     (select dietstartdate from Users where userid = 190)
     and GETDATE()) t where Row=1
于 2013-06-05T08:51:25.720 回答