【问题标题】:Column 'VacationsTable.StartDate' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause列 \'VacationsTable.StartDate\' 在选择列表中无效,因为它未包含在聚合函数或 GROUP BY 子句中
【发布时间】:2023-01-16 04:49:35
【问题描述】:

我正在尝试创建一个程序,用户在文本框中输入一个月并按下按钮,向用户显示假期数据库中所有城市的每晚平均价格数据。 例如: 阿姆斯特丹:134.44 并且当开始日期与输入的月份相同并且结束日期不计算用户输入的月份中的第几天时,反之亦然

这是我的程序:

ALTER PROCEDURE sp_AdminAvgPriceMonth
    -- Add the parameters for the stored procedure here
    @month int
AS
BEGIN

    -- Insert statements for procedure here
    select case 
                when month(StartDate)= @month and month(EndDate)=@month
                then avg(datediff(day, StartDate, EndDate)*price)
                when month(StartDate)=@month and month(EndDate)<>@month
                then avg(datediff(day, StartDate, EOMONTH(StartDate))*price)
                     --month(StartDate)<>@month and month(EndDate)=@month 
                else avg(datediff(day, DATEADD(month, DATEDIFF(month, 0, StartDate), 0), EndDate)*price)
                end as avrgPrice
    from VacationsTable VT inner join FlatsTable FT on VT.FlatId=FT.FlatId
    group by City

【问题讨论】:

    标签: sql-server stored-procedures


    【解决方案1】:

    我没有检查你的逻辑,但你可能需要将你的CASE语句移动到你的AVG()语句中......就像错误消息解释的那样,StartDate不在你的聚合中。尝试像下面这样构造

    select avg( case  
                when month(StartDate)= @month and month(EndDate)=@month
                then (datediff(day, StartDate, EndDate)*price) --etc
    

    如果您没有进一步的错误,然后检查您的逻辑。

    有时,我发现使用子查询、CTE 或临时表结果将您的业务公式逻辑与报告聚合逻辑分开会很有帮助。所以考虑一下,如果它有帮助的话。

    【讨论】:

      猜你喜欢
      • 2022-12-06
      • 1970-01-01
      • 2011-07-04
      • 2013-08-17
      相关资源
      最近更新 更多