2012-11-13 175 views
3

我需要做一個複雜的查詢,我需要幫助。下面是我有什麼一個例子:[來到這裏的SQL]SQLite的複雜SQL查詢

id | Date | Validity 

48 | 6-1-2009 | notFound 
47 | 6-1-2009 | valid 
46 | 6-1-2009 | valid  
45 | 3-1-2009 | invalid 
44 | 3-1-2009 | invalid 
42 | 4-1-2009 | notFound 
41 | 4-1-2009 | notFound 
48 | 4-1-2009 | valid 

,查詢結果將如下所示:

Date | valid | invalid | notFound 

3-1-2009 | 0  |  2  |  0 
4-1-2009 | 1  |  2  |  2 
6-1-2009 | 3  |  2  |  3 

我只能在SQLite的做到這一點?有人能幫我嗎?我在Python工作。

我需要這個來產生一個線圖。例如:line chart

+0

不,你不能在SQL獨自做到這一點。這就是Python的作用:從數據庫獲取數據後,對數據做些什麼。 – pydsigner

回答

1

您的Date列無法正確排序,因爲它不是從最重要的字段開始的。

假設你改變有一個正確的yyyy-mm-dd格式的日期,你可以使用這樣的事情:

SELECT A.Date, 
     (SELECT COUNT(*) FROM MyTable AS B 
     WHERE B.Date <= A.Date 
      AND B.Validity = 'valid') AS valid, 
     (SELECT COUNT(*) FROM MyTable AS B 
     WHERE B.Date <= A.Date 
      AND B.Validity = 'invalid') AS invalid, 
     (SELECT COUNT(*) FROM MyTable AS B 
     WHERE B.Date <= A.Date 
      AND B.Validity = 'notFound') AS notFound 
FROM (SELECT DISTINCT Date FROM MyTable 
     ORDER BY Date) AS A 
+0

你的答案完美無缺!謝謝! – Viktor

4

我相信這應該這樣做:

SELECT Date, 
SUM(Validity = "valid") AS valid, 
SUM(Validity = "invalid") AS invalid, 
SUM(Validity = "notFound") AS notFound 
FROM table_name 
GROUP BY Date 

SUM函數將相符的各種有效性類型的總數。 '='函數在false時返回0,在true時返回1,這就是允許它工作的原因。

**編輯**

我才意識到,這是不太你想要什麼,你正在尋找的,其中還包括從以前的日期數據的每個日期的整體集合體。這可以在python中很容易地完成。

valid_sum = 0 
invalid_sum = 0 
notfound_sum = 0 
for r in cursor.fetchall(): 
    date = r[0] 
    valid_sum += int(r[1]) 
    invalid_sum += int(r[2]) 
    notfound_sum += int(r[3]) 
    # print aggregate data for this date