3

我需要做一个复杂的查询,我需要帮助。以下是我拥有的示例:

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 

[这里是 SQL。]

查询结果如下所示:

   Date   |  valid   |  invalid   |    notFound

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

我只能在 SQLite 中执行此操作吗?有人能帮我吗?我正在使用 Python。

我需要这个来生成一个折线图。例如:折线图

4

2 回答 2

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
于 2012-11-13T01:43:16.073 回答
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
于 2012-11-13T08:13:20.520 回答