SQLite:尝试以比UNION字符串更优雅的方式连接列

时间:2014-06-23 18:32:32

标签: sqlite unions group-concat

我有一个包含以下字段和示例值的表:

coursecode  BIO 101
a_code      FA
b_code      SP
c_code      SU
d_code
e_code

我正在尝试使用逗号分隔的列表来填充另一个表中的字段(使用课程代码作为键),该字段具有值(即“FA,SP,SU”)的所有“代码”字段。我使用下面的代码成功完成了这个,但它很乱,并且想知道是否有更优雅的方法来实现这一点(特别是没有所有的UNION语句):

SELECT coursecode, group_concat(codes)
FROM (
SELECT 
    coursecode, 
    a_code AS codes
FROM scbsupp
    WHERE coursecode="BIO 317"
UNION
SELECT coursecode,
    b_code AS codes
FROM scbsupp
    WHERE coursecode="BIO 317" 
UNION
SELECT 
    coursecode, 
    c_code AS codes
FROM scbsupp
    WHERE coursecode="BIO 317"
UNION
SELECT coursecode,
    d_code AS codes
FROM scbsupp
    WHERE coursecode="BIO 317"
UNION
SELECT coursecode,
    e_code AS codes 
FROM scbsupp
    WHERE coursecode="BIO 317"
) WHERE codes != "";    

据我所知,我想知道是否有更好的方法,我感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

你可以这样做:

SELECT coursecode,
      LTRIM(
              CASE WHEN (a_code IS NOT NULL AND a_code <> '') THEN        a_code ELSE '' END ||
              CASE WHEN (b_code is NOT NULL AND b_code <> '') THEN ',' || b_code ELSE '' END ||
              CASE WHEN (c_code IS NOT NULL AND c_code <> '') THEN ',' || c_code ELSE '' END ||
              CASE WHEN (d_code IS NOT NULL AND d_code <> '') THEN ',' || d_code ELSE '' END ||
              CASE WHEN (e_code IS NOT NULL AND e_code <> '') THEN ',' || e_code ELSE '' END, ','
            )   AS code
  FROM scbsupp
    WHERE coursecode="BIO 317"