Postgresql postgres复杂查询
我不知道有没有可能提出这样的质疑。问题是我有一个表格,里面有一些日期的数字。 假设我有3列:日期、值、好/坏 即: 我想选择并减去好的和坏的:Postgresql postgres复杂查询,postgresql,select,subtraction,Postgresql,Select,Subtraction,我不知道有没有可能提出这样的质疑。问题是我有一个表格,里面有一些日期的数字。 假设我有3列:日期、值、好/坏 即: 我想选择并减去好的和坏的: 2014-03-03 85 2014-03-04 110 可能吗?我想了很多,现在还不知道。如果我在不同的表中有好的值和坏的值,那就很简单了。诀窍是将您的表连接回它自己,如下所示myTable as A将仅读取Good行,而myTable as B将仅读取Bad行。然后,这些行将根据日期合并到一个单行中 返回的输出: DATE
2014-03-03 85
2014-03-04 110
可能吗?我想了很多,现在还不知道。如果我在不同的表中有好的值和坏的值,那就很简单了。诀窍是将您的表连接回它自己,如下所示
myTable as A
将仅读取Good
行,而myTable as B
将仅读取Bad
行。然后,这些行将根据日期
合并到一个单行中
返回的输出:
DATE GOOD_COUNT BAD_COUNT DIFF_COUNT
March, 03 2014 00:00:00+0000 100 15 85
March, 04 2014 00:00:00+0000 120 10 110
另一种方法是使用groupby
而不是内部连接
:
select
a.date
,sum(case when type = 'Good' then a.count else 0 end) as Good_count
,sum(case when type = 'Bad' then a.count else 0 end) as Bad_count
,sum(case when type = 'Good' then a.count else 0 end) -
sum(case when type = 'Bad' then a.count else 0 end) as Diff_count
from myTable as a
group by a.date
order by a.date
两种方法产生相同的结果。是否正好有2行,1行。好的,2点。不好,对于每个日期?注意:第一个解决方案将在只有“好”或“坏”观察结果存在的天数内失败。我终于测试了你的答案。在我的例子中,一种方法失败的情况是不应该发生的,在你给出第二种方法之前,我已经用过了:)它的工作原理与假设的工作原理完全相同。非常感谢:)
DATE GOOD_COUNT BAD_COUNT DIFF_COUNT
March, 03 2014 00:00:00+0000 100 15 85
March, 04 2014 00:00:00+0000 120 10 110
select
a.date
,sum(case when type = 'Good' then a.count else 0 end) as Good_count
,sum(case when type = 'Bad' then a.count else 0 end) as Bad_count
,sum(case when type = 'Good' then a.count else 0 end) -
sum(case when type = 'Bad' then a.count else 0 end) as Diff_count
from myTable as a
group by a.date
order by a.date