如何在子查询中引用结果

时间:2016-12-06 18:31:32

标签: sqlite subquery

我在sqlite数据库中有下表

+----+-------------+-------+
| ID | Week Number | Count |
+----+-------------+-------+
|  1 |           1 |    31 |
|  2 |           2 |    16 |
|  3 |           3 |    73 |
|  4 |           4 |    59 |
|  5 |           5 |    44 |
|  6 |           6 |    73 |
+----+-------------+-------+

我想得到下表。我将本周销售作为一个专栏,然后下一个专栏将是上周销售。

+-------------+-----------+-----------+
| Week Number | This_Week | Last_Week |
+-------------+-----------+-----------+
|           1 |        31 | null      |
|           2 |        16 | 31        |
|           3 |        73 | 16        |
|           4 |        59 | 73        |
|           5 |        44 | 59        |
|           6 |        73 | 44        |
+-------------+-----------+-----------+

这是我要使用的select语句:

select 
    id, week_number, count, 
    (select count from tempTable 
     where week_number = (week_number-1)) 
from 
    tempTable;

2 个答案:

答案 0 :(得分:1)

您正在比较两个不同行中的值。当您只是写week_number时,数据库不知道您的意思。

要引用特定表格中的列,您必须在其前面加上表格名称:tempTable.week_number

如果两个表具有相同的名称,则必须至少重命名其中一个:

SELECT id,
       week_number,
       count AS This_Week,
       (SELECT count
        FROM tempTable AS T2
        WHERE T2.week_number = tempTable.week_number - 1
       ) AS Last_Week
FROM tempTable;

答案 1 :(得分:0)

如果您想要对同一个表进行两次查询,则必须将别名放在原始别名上并将其复制以区分它们

select a.week_number,a.count this_week,
      (select b.count from tempTable b 
        where b.week_number=(a.week_number-1)) last_week
  from tempTable a;