2011-12-28 26 views
4

我有簡單的表:選擇帶有字段總和的所有項目在規定的範圍內

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) 
+1

什麼是您預期的結果?我不清楚。 – 2011-12-28 14:47:27

+0

找到所有在指定範圍FILE_SIZE的總和老(由file_time)項目。我的原始查詢是確定的,而file_time是唯一的。 – user1119412 2011-12-28 17:05:46

+0

它對我來說工作得很好,就像你想要的那樣。 – 2011-12-28 19:01:05

回答

1

你不應該考慮file_time爲您查詢的單列,因爲你想要考慮列file_id要麼。您應該使用對file_timefile_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 
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; 
+0

您的查詢甚至沒有獨特file_time工作(19,20,21,22 ...) – user1119412 2011-12-28 17:07:24

+0

你的意思是它不工作,即錯誤或者說,它沒有做你想要什麼? – 2011-12-28 17:30:06

+0

沒有錯誤(sqlite不支持TOP - 它被LIMIT取代)。查詢的結果是錯誤的。工作查詢:SELECT SUM(file_size)AS sum_file_size,file_time,file_id從第一個 WHERE(file_time <=(從file_time開始的第一個文件時間限制1))AND(first.file_size BETWEEN 1和7)GROUP BY first.file_time ;。對於對FILE_SIZE,file_time - {{1,18},{2,19},{3,20},{4,21},{5,22}}我想{{1,18},{2 ,19},{3,20}}。但是你的查詢返回{1,18}。 – user1119412 2011-12-28 17:47:22

相關問題