如何在sqlite中使用别名进行算术运算
How to do arithemtic operations with an alias in sqlite
我想在 sqlite 中使用别名进行计算(示例修改自 http://www.sqlitetutorial.net):
如果我这样做,我会收到错误消息 "no such column: tracks_count"
SELECT albumid,
title,
(
SELECT count(trackid)
FROM tracks
WHERE tracks.AlbumId = albums.AlbumId
)
tracks_count, tracks_count * album_nr
FROM albums
ORDER BY tracks_count DESC;
如果我这样做,我的多重运算为零
SELECT albumid,
title,
(
SELECT count(trackid)
FROM tracks
WHERE tracks.AlbumId = albums.AlbumId
)
tracks_count, "tracks_count" * album_nr
FROM albums
ORDER BY tracks_count DESC;
Table 示例数据:
table 专辑
table 曲目
这里甚至不需要子查询:
SELECT
a.albumid,
a.title,
COUNT(t.albumid) AS tracks_count,
COUNT(t.albumid) * a.album_nr AS other_count
FROM albums a
LEFT JOIN tracks t
ON a.albumid = t.albumid
GROUP BY
a.albumid,
a.title;
如果您想让当前的方法起作用,那么您遇到的问题是您在定义别名的同一个 select 中引用了 tracks_count
别名。这是不允许的,因为别名可能还没有计算出来。但是,我建议使用上面给出的答案。
我想在 sqlite 中使用别名进行计算(示例修改自 http://www.sqlitetutorial.net):
如果我这样做,我会收到错误消息 "no such column: tracks_count"
SELECT albumid,
title,
(
SELECT count(trackid)
FROM tracks
WHERE tracks.AlbumId = albums.AlbumId
)
tracks_count, tracks_count * album_nr
FROM albums
ORDER BY tracks_count DESC;
如果我这样做,我的多重运算为零
SELECT albumid,
title,
(
SELECT count(trackid)
FROM tracks
WHERE tracks.AlbumId = albums.AlbumId
)
tracks_count, "tracks_count" * album_nr
FROM albums
ORDER BY tracks_count DESC;
Table 示例数据:
table 专辑
table 曲目
这里甚至不需要子查询:
SELECT
a.albumid,
a.title,
COUNT(t.albumid) AS tracks_count,
COUNT(t.albumid) * a.album_nr AS other_count
FROM albums a
LEFT JOIN tracks t
ON a.albumid = t.albumid
GROUP BY
a.albumid,
a.title;
如果您想让当前的方法起作用,那么您遇到的问题是您在定义别名的同一个 select 中引用了 tracks_count
别名。这是不允许的,因为别名可能还没有计算出来。但是,我建议使用上面给出的答案。