select 语句中的列无法识别

Column not recognized in select statement

我在这段代码的 Select 语句中遇到错误。

SELECT Track.Name, Track.UnitPrice, 
    Count(*) AS Purchase_count, 
    Purchase_count * Track.UnitPrice AS Total_per_track
FROM Track
JOIN InvoiceLine ON Track.TrackId = InvoiceLine.TrackId
GROUP BY Track.Name
ORDER BY  Total_per_track desc
LIMIT 10;

返回的错误是

Result: no such column: Purchase_count
At line 1:
SELECT Track.Name, Track.UnitPrice, 
    Count(*) AS Purchase_count, 
    Purchase_count * Track.UnitPrice AS Total_per_track
    FROM Track
    JOIN InvoiceLine
    ON Track.TrackId = InvoiceLine.TrackId
    GROUP BY Track.Name
    ORDER BY  Total_per_track desc
LIMIT 10;

您不能在同一子句中引用 SELECT 子句中定义的别名(例如 WHERE 子句中也不能)。您需要重复原始表达式,或使用派生的 table (子查询或 cte)。

这里的表达很简单,所以重复似乎更相关:

SELECT 
    t.Name, 
    t.UnitPrice, 
    COUNT(*) AS Purchase_count, 
    COUNT(*) * t.UnitPrice AS Total_per_track
FROM Track t
INNER JOIN InvoiceLine il ON t.TrackId = il.TrackId
GROUP BY t.TrackId, t.Name, t.UnitPrice
ORDER BY Total_per_track desc
LIMIT 10;

备注:

  • 我在 GROUP BY 子句中添加了 TrackIdUnitPriceTrackId 是为了避免错误地将两个具有相同 Name 的轨道组合在一起; UnitPrice 出现在 SELECT 子句中并且不是聚合函数的一部分,因此最好将它也放在 GROUP BY 子句中(尽管它在功能上看起来确实依赖于 TrackId)

  • table 别名使查询更短,便于读写

为了按 Total_per_track 排序,您需要使用 table 表达式

例如:

select *
from (
  SELECT
    Track.Name, Track.UnitPrice, 
    Count(*) AS Purchase_count, 
    Count(*) * Track.UnitPrice AS Total_per_track
  FROM Track
  JOIN InvoiceLine
  ON Track.TrackId = InvoiceLine.TrackId
  GROUP BY Track.Name
) x
ORDER BY Total_per_track desc
LIMIT 10