我想总结一个案例的发生。我试图在案例陈述中使用总和,但我得到了这个错误,怎么解决?
Msg 130, Level 15, State 1, Line 3
Cannot perform an aggregate function on an expression containing an aggregate or a subquery.
我的代码示例:
select
sum(case when cast(max(ptl.RowDate)as int) = cast(Min(ptl.RowDate) as int) then 1 else 0 end)
,DATEPART(WEEK, rowdate) week_
from m.dbo.tblLog ptl (nolock)
where rowdate > GETDATE()-91
group by DATEPART(WEEK, rowdate)
更新: 基于评论:我想计算仅访问网页的不同用户一次。我希望根据每周时间框架获取计数。
答案 0 :(得分:1)
您不能在另一个内部使用聚合函数。您需要使用子查询或CTE:
SELECT SUM(something) as s,
week_
FROM (
select case when cast(max(ptl.RowDate)as int) = cast(Min(ptl.RowDate) as int) then 1 else 0 end as something,
DATEPART(WEEK, rowdate) week_
from m.dbo.tblLog ptl (nolock)
where rowdate > GETDATE()-91
group by DATEPART(WEEK, rowdate)
) as res
GROUP BY week_
答案 1 :(得分:1)
查询的替代方式
SELECT SUM(CASE WHEN CAST(MaxRowDate AS INT) = cast(MinRowDate AS INT) THEN 1 ELSE 0 END)
week_
FROM
(
SELECT MAX(ptl.RowDate) MaxRowDate,MIN(ptl.RowDate) MinRowDate,DATEPART(WEEK, rowdate) week_
FROM m.dbo.tblLog ptl (NOLOCK)
WHERE rowdate > GETDATE()-91
GROUP BY DATEPART(WEEK, rowdate)
)M
GROUP BY week_
答案 2 :(得分:1)
如果您只想要一面旗帜,为什么还要sum()
:
select (case when cast(max(ptl.RowDate)as int) = cast(Min(ptl.RowDate) as int)
then 1 else 0
end) as OneValueFlag,
DATEPART(WEEK, rowdate) as week_
from m.dbo.tblLog ptl (nolock)
where rowdate > GETDATE() - 91
group by DATEPART(WEEK, rowdate);
还完全不清楚为什么将价值转换为日期:
select (case when max(ptl.RowDate) = Min(ptl.RowDate)
then 1 else 0
end) as OneValueFlag,
DATEPART(WEEK, rowdate) as week_
from m.dbo.tblLog ptl (nolock)
where rowdate > GETDATE() - 91
group by DATEPART(WEEK, rowdate);