【问题标题】:PostgreSQL, SQL: Compare values in one column in the table and return multiple columns by the conditionPostgreSQL、SQL:比较表中一列的值并按条件返回多列
【发布时间】:2021-03-11 09:15:58
【问题描述】:

我有一张有几行的表。 我需要检查:如果列索引中的所有值都相等,那么得到三个具有唯一值的列, 如果值不相等,则得到一个空表。 例如,如果索引相等: 输入

index   Product Version
10        A      2.5
10        A      2.5  
10        A      2.5

输出

index   Product Version
10        A      2.5

例如,如果索引不相等: 输入:

index   Product      Version
10          A          2.5
11          B          3.3
10          A          2.5
10          A          2.5

输出

index   Product      Version

我尝试使用“Case When”语句来做到这一点,但“Case When”只能返回单列。 有没有办法比较一列中的值并返回几列?

【问题讨论】:

  • 。 .如果您有一个返回多行的示例,您的问题会更清楚。

标签: sql postgresql


【解决方案1】:

demo: all records equal

demo: records not equal

SELECT
    *
FROM (
    SELECT
        *,
        row_number() OVER (PARTITION BY index, product, version),
        count(*) OVER ()
    FROM mytable
) s
WHERE row_number = count

为每个列组添加行数。如果所有记录相等,则最大行数等于全部记录数。

所以只返回与总计数具有相同行号的记录。如果不是所有记录都相等,则该记录将不存在并返回一个空表。

【讨论】:

    【解决方案2】:

    嗯。 . .这可能是你的想法:

    select distinct index, product, version
    from t
    where not exists (select 1
                      from t t2
                      where t2.index <> t.index
                     );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多