【问题标题】:posgresql selecting two different data as two columns from one columnpostgresql 从一列中选择两个不同的数据作为两列
【发布时间】:2021-01-21 10:08:48
【问题描述】:

我需要从stockcurrent 中选择两个 id 作为两个不同的列 (id1,id2),第一个是 points.id = '244',第二个是 points.id ='191'。但结果面对最后一个where 子句,并根据该语句仅填充一列。

我想我遇到了与这种情况类似的问题:Two SELECT statements as two columns
唯一的区别是,在上面的例子中,他的最后一个where 子句在范围内,但我的不在范围内。在我看来,这就是我的声明不起作用的原因:

select
(case when po.id='244' then st.id end) id1,
 (case when po.id='191' then st.id end) id2
from stockcurrent st
inner join points po on po.id = st.point
where po.id ='244';

我的结果:

预期结果:

所以我需要找到一种解决方案来用id填充两列,而不仅仅是一个在这种情况下给我'244'的结果。提前致谢。
stockcurrent 表示例:

+-------+-------+
|  id   | point |
+-------+-------+
| 23414 |   191 |
| 12493 |   191 |
| 16121 |   170 |
| 24325 |   191 |
| 51232 |   244 |
| 11255 |   244 |
| 56572 |   244 |
| 16123 |   170 |
+-------+-------+

points 表示例:

+-----+------+------+
| id  | comp | type |
+-----+------+------+
| 191 |   96 |    2 |
| 307 |   96 |    1 |
| 244 |   97 |    0 |
| 311 |   98 |    0 |
| 170 |  109 |    0 |
+-----+------+------+

【问题讨论】:

  • 样本数据最好显示为formatted text。请参阅here,了解有关如何创建漂亮表格的一些提示。
  • 如果你加入 po.id = st.point 那么在 stoccurrent 中每行只能有一个 point.id 值,所以我不知道你在问什么。
  • where po.id in ('244', '191');
  • @bobflux 好的,也许 join 不正确,我尝试的整个代码方向错误,但还有其他方法可以实现我想要的吗?也许是子查询或联合,​​不幸的是,我对 SQL 的信心很差。结果,我需要创建一个包含两列的 select 语句,一个用于 id ,其中点为 244,第二个 id 为 191。
  • @adrianKlaver 您的解决方案运行良好,实际上,它解决了问题。我在猜测为什么您的解决方案给了我空的 [null] 字段,但后来意识到这只是因为并非我需要找到的每个 id 都有适当的点。这就是为什么我认为您的答案不正确的原因。您可以将其发布为答案吗?

标签: postgresql


【解决方案1】:

将查询更改为:

select
(case when po.id='244' then st.id end) id1,
 (case when po.id='191' then st.id end) id2
from stockcurrent st
inner join points po on po.id = st.point
where po.id in ('244', '191');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-14
    • 1970-01-01
    • 2017-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多