错误代码:1054。'where clause' 中的未知列 'sdate'

Error Code: 1054. Unknown column 'sdate' in 'where clause'

我在查询中遇到了这个错误,您知道如何将 sdate 放入 2 层子查询中吗?

select
at.startDate as sdate, at.dau as DAU,
(
select count(distinct d.uid) from
 (select ses.uid from dsession as ses where ses.startDate = sdate group by ses.uid
  union all
  select res.uid from rsession as res where res.startDate = sdate group by res.uid) as te
) as MAU, (SELECT DAU/MAU) as AVG
from
attendance as at 

如果我单独查询子查询它会工作,但是当我将它合并到主查询时,sdate 变得未知。有什么想法吗?

我试图将 where 上的 sdate 替换为 at.startDate,但仍然得到未知的 at.startDate 列。

您不能在 where 子句中使用列别名。只用原来的列名:

where at.startDate between @startDate and @endDate 

别名 已被 order by 接受,因此无需更改。

我没有在主 select 子句中使用 selects,而是创建了一个子查询来加入,以便可以检查 startDate

SELECT at.startDate AS sdate, at.dau AS DAU, (DAU/MAU.cnt) as AVG
FROM attendance AS at
JOIN (SELECT startdate, count(distinct uid) as cnt
      FROM (SELECT uid, startdate FROM dsession
            UNION ALL
            SELECT uid, startdate FROM rsession) as ua
      GROUP BY startdate
     ) as MAU ON MAU.startdate = at.startdate

希望我在重构查询时没有搞砸任何事情 :)