PostgreSQL视图嵌入if语句

时间:2012-01-04 15:18:11

标签: postgresql view

在我的数据库中,对于没有来自经销商评级的评分的商店,他们仍然有一个条目,但-1.0而不是0.010.0之间的数字。以下查询结果显示-10.00在我的视图中显示-1.0的商店。相反,我想要一个或者-出现在它的位置,但我不太习惯在我的视图中实现嵌入式if语句。这是我目前的观点。

CREATE VIEW myview AS
SELECT co_url_name AS company_url, score_combined AS stella_score, trunc(score*10, 2) AS bizrate_score,
(SELECT trunc("lifetimeRating"*10, 2)) AS resellerRating_score
    FROM ss_profile_co AS s LEFT OUTER JOIN "resellerRatings_ratings" AS r
        ON s.id = r.company_id
            LEFT OUTER JOIN (SELECT * FROM bizrate_bizrate_ratings WHERE score_name = 'Overall rating') AS b
                ON s.id = b.fk_co_id
                    ORDER BY co_url_name ASC;

(SELECT trunc("lifetimeRating"*10, 2)) AS resellerRating_score是返回负数的行(或者,对于有效条目,将返回0.00100.00之间的分数。

显然,我可以简单地从数据库中删除导致这些条目的这些条目,但这只是学习经验的一半,而且无论如何都有一半不在我手中。

我很感激帮助!

编辑:尝试嵌入式,但不出意外地出现错误。

IF (SELECT trunc("lifetimeRating"*10, 2)) = -10.00 THEN NULL ELSE (SELECT trunc("lifetimeRating"*10, 2)) AS resellerRating_score

EDIT2:想出来了。有问题的行如下:

(SELECT trunc("lifetimeRating"*10, 2) WHERE trunc("lifetimeRating"*10, 2) > 0) AS resellerrating_score

/ foreveralone

1 个答案:

答案 0 :(得分:2)

看起来像这样:

CREATE VIEW myview AS
SELECT co_url_name AS company_url
      ,score_combined AS stella_score
      ,trunc(score * 10, 2) AS bizrate_score
      ,CASE WHEN "lifetimeRating" < 0
            THEN NULL
            ELSE trunc("lifetimeRating" * 10, 2)
       END AS resellerRating_score
FROM   ss_profile_co s
LEFT   JOIN "resellerRatings_ratings" r ON r.company_id = s.id
LEFT   JOIN bizrate_bizrate_ratings   b ON b.score_name = 'Overall rating' 
                                        AND b.fk_co_id = s.id
ORDER  BY co_url_name;

重点

  • 关于您的核心问题:没有FROM子句的子选择没有任何意义。我简化了这一点并改为使用CASE语句。

  • 我还将您的LEFT JOIN简化为bizrate_bizrate_ratings。也没有必要的子选择。我将WHERE条款提升到JOIN条件。更简单,更快捷。

  • 我建议不要使用mixed case identifiers,因此您永远不必使用双引号。 (这可能会使@Daniels评论无效,因为lifetimerating!= "lifetimeRating"