我有简单的表格:
file_size file_id file_time
1 1 19
2 2 20
3 3 21
4 4 22
5 5 23
我想找到这样的项目,即file_time较少的所有项目都具有预定义范围内的file_size之和。 我写了下一个查询:
SELECT * FROM test_table AS D0 WHERE
(SELECT TOTAL(file_size) FROM test_table AS D1 WHERE
D1.file_time <= D0.file_time ORDER BY file_id)
BETWEEN 1 AND 9
此查询可获得正确的结果:
1 1 19
2 2 20
3 3 21
但是如果所需的项具有相同的file_time字段,则此查询不起作用:
file_size file_id file_time
1 1 20
2 2 20
3 3 20
4 4 20
5 5 20
此数据的预期结果是:
1 1 20
2 2 20
3 3 20
file_id字段是唯一的。 我的SQL查询有什么问题?
创建测试表的代码:
CREATE TABLE test_table (file_size INT, file_id INT, file_time INT)
INSERT INTO test_table VALUES(1,1,20)
INSERT INTO test_table VALUES(2,2,20)
INSERT INTO test_table VALUES(3,3,20)
INSERT INTO test_table VALUES(4,4,20)
INSERT INTO test_table VALUES(5,5,20)
答案 0 :(得分:1)
您不应将file_time
视为查询中的单个列,因为您还要考虑列file_id
。您应该使用file_time
和file_id
对,您应该按字典顺序对它们进行比较,如下所示:
SELECT *
FROM test_table AS D0
WHERE (
SELECT TOTAL( file_size )
FROM test_table AS D1
WHERE D1.file_time < D0.file_time
OR (
D1.file_time = D0.file_time
AND D1.file_id <= D0.file_id
)
ORDER BY file_time, file_id DESC
)
BETWEEN 1
AND 9
答案 1 :(得分:0)
不确定我是否理解,但我认为
-- sum of file sizes between 1 and 7 with the lowest time
SELECT SUM(test.file_size) AS sum_file_size, test.file_time
FROM test
WHERE (test.file_time = (SELECT TOP 1 test.file_time
FROM test
ORDER BY file_time))
AND (test.file_size BETWEEN 1 AND 9)
GROUP BY test.file_time;
-- sum of file sizes per time `group`
SELECT SUM(test.file_size) AS sum_file_size, test.file_time,
FROM test
WHERE (test.file_size BETWEEN 1 AND 7)
GROUP BY test.file_time
ORDER BY test.file_time;