我有一张这样的表:
USER PERIOD SCORE
A 1 8
A 1 9
A 2 2
A 2 3
A 3 4
A 3 5
B 1 2
B 1 3
B 2 5
B 2 4
B 3 4
B 3 4
C 1 2
C 1 3
C 2 3
C 2 5
C 3 3
C 3 4
我需要计算每个用户每个时段的平均得分,因此我需要将表转换为此
USER PERIOD SCORE
A 1 8.5
A 2 2.5
A 3 4.5
B 1 2.5
B 2 4.5
B 3 4
C 1 2.5
C 2 4
C 3 3.5
然后最后,我需要创建一个只有每个时期得分最高的表和相应的用户,就像这样
USER PERIOD SCORE
A 1 8.5
B 2 4.5
A 3 4.5
我可以通过创建两个表来实现这一点,但我想成为一个高级查询主义者,并且只需一步即可完成。有什么指针吗?这些是我目前的疑问:
CREATE TABLE STEP1 AS SELECT
USER
,PERIOD
,AVG(SCORE) AS SCORE
FROM STEP0
GROUP BY 1,2
;
CREATE TABLE STEP2 AS SELECT
PERIOD
,MAX(SCORE) AS SCORE
FROM STEP1
GROUP BY 1
;
CREATE TABLE FINAL AS SELECT
A.USER
,B.PERIOD
,B.SCORE
FROM STEP1 A
JOIN STEP2 B
ON A.SCORE=B.SCORE
;
我正在使用SQLite数据库浏览器,但如果我要求使用它无法完成,即我们需要SQLite数据库浏览器中没有的功能,我可以使用另一个SQL应用程序。
答案 0 :(得分:0)
尝试使用$v
:
NOT EXISTS()
答案 1 :(得分:0)
INSERT INTO STEP1
SELECT users, Period, AVG(CAST(score AS float)) AS score
FROM TEST a
GROUP BY users, Period
SELECT * FROM STEP1
INSERT INTO STEP2
SELECT
A.Period,
Max(A.score) as score
FROM
STEP1 A
GROUP BY A.Period
SELECT * FROM STEP2
INSERT INTO FINAL
SELECT A.users, A.Period, A.score
FROM STEP1 A
INNER JOIN STEP2 B ON A.score = B.score AND A.Period = B.Period
SELECT * FROM FINAL