SQL Select;连接字符串,避免列为空的双逗号?

时间:2011-11-26 17:59:17

标签: sql oracle select

我有以下参考数据。

PERSON_NAME                    STREET                   TOWN             COUNTY           POSTCODE   
------------------------------ ------------------------ ---------------- ---------------- ---------- 
David Smith                    30 Johnson Street        Norwich          Norfolk          NA38 3KL   
John Brown                     Douglas Road             Cambridge                         C8  9IJ    
Jackie White                   8 High Street            Ipswich          Suffolk          IP7  2YT   
Andrea Blue                    9 Marlborough Ave        Bury             Suffolk          IP4  0XC   
Jemima Green                   Riverside Walk           Colchester       Essex            CO6  7PR   
James Gray                     167 Hadleigh Place       London                            SW1 4TU  

我想要做的是显示一个人名列表,以及它们连接成逗号分隔字符串的地址。

这部分很简单,我使用||来连接列并放置逗号分隔符。

我正在质疑的部分是,某些行没有为COUNTY列出任何内容,因此我需要避免显示, ,

我已经为自己做了一些研究,并决定使用Oracle中的SUBSTR替换双逗号,但它确实感觉有点“脏”。有没有更简洁的方法来避免使用复杂的功能(例如this previous SO question)?

这就是我所拥有的:

SELECT
    SUPPNAME as "Supplier Name",
    REPLACE(STREET || ', ' || TOWN || ', ' || COUNTY || ', ' || POSTCODE, ' ,','') as "Supplier Address"
FROM
    SUPPLIERS
;

由于

3 个答案:

答案 0 :(得分:7)

SELECT
SUPPNAME AS "Supplier Name",
(
CASE WHEN STREET IS NULL THEN '' ELSE STREET || ', ' END || 
CASE WHEN TOWN IS NULL THEN '' ELSE TOWN || ', ' END ||
CASE WHEN COUNTY IS NULL THEN '' ELSE COUNTY || ', ' END || 
CASE WHEN POSTCODE IS NULL THEN '' ELSE POSTCODE END
) AS "Supplier Address"
FROM SUPPLIERS

答案 1 :(得分:3)

在之前的答案中,如果所有的fiield都是NULL,那么你只会得到愚蠢的','而是预期的NULL。尝试这种方法在结果开始时删除一个额外的','

SELECT
SUPPNAME AS "Supplier Name",
SUBSTR(
    NVL2(STREET, ', ' || STREET, NULL)
        || NVL2(TOWN, ', ' || TOWN, NULL)
        || NVL2(COUNTY, ', ' || COUNTY, NULL)
        || NVL2(POSTCODE, ', ' || POSTCODE, NULL)
    ,2) AS "Supplier Address"
FROM SUPPLIERS

答案 2 :(得分:2)

您可以在可能为空的字段周围使用NVL2,例如NVL2(county, county || ',', '')