我有这个查询在MYSQL中工作,但不能在SQLite中运行。我认为它失败是因为WHERE子句中有多个参数。
目的是为所有调查问题(sqid)选择唯一的最新调查答案(所述),因为可能会有多个问题答案。
SELECT sqid, said, saname, satimestamp
FROM surveyanswer
WHERE (sqid, hoid, satimestamp) IN (
SELECT sqid, hoid, max(satimestamp) as satimestamp
FROM surveyanswer
GROUP BY sqid
)
我已经尝试过satimestamp的排序并选择了一个而不是max的限制但是无法使其工作。
答案 0 :(得分:2)
您可以通过加入来执行此操作:
SELECT sqid, said, saname, satimestamp
FROM surveyanswer A
JOIN (
SELECT sqid, hoid, max(satimestamp) as satimestamp
FROM surveyanswer
GROUP BY sqid
) B ON A.sqid = B.sqid and A.hoid = B.hoid and A.satimestamp = B.satimestamp
这在功能上与原始SQL类似,但由于您只关心时间,我相信这也会起作用:
SELECT sqid, said, saname, satimestamp
FROM surveyanswer A
JOIN (
SELECT max(satimestamp) as satimestamp
FROM surveyanswer
) B ON A.satimestamp = B.satimestamp
答案 1 :(得分:2)
您似乎没有使用hoid
字段进行任何操作。所以,我删除了它。以下是否能满足您的需求:
SELECT sa.sqid, sa.said, sa.saname, sa.satimestamp
FROM surveyanswer sa
WHERE sa.satimestamp IN (
SELECT max(subsa.satimestamp)
FROM surveyanswer subsa
WHERE sa.sqid = subsa.sqid
)
如果hoid
字段需要包含在where子句中,请尝试以下操作:
SELECT sa.sqid, sa.said, sa.saname, sa.satimestamp
FROM surveyanswer sa
WHERE sa.satimestamp IN (
SELECT max(subsa.satimestamp)
FROM surveyanswer subsa
WHERE sa.sqid = subsa.sqid
AND sa.hoid = subsa.hoid
)