在SQL

时间:2016-07-18 16:41:52

标签: mysql sql hana

我有一个包含3列的表

A.          B.           C.   
Abc.      Abc.           1
Abc.      Abc.           2 
Abc.      Abc.           3
Bcd.      Bcd.           4
Cde.      Cde.           2
Cde.      Cde.           4
Cde.      Cde.           4    

我想将它们作为单行创建,如下所示

A.           B.            C.   
Abc.       Abc.          1/2/3/-
Bcd.       Bcd.          -/-/-/4
Cde.       Cde.         -/2/-/4

任何人都可以帮帮我吗? C列的最大数量为4。所以最好的情况是1/2/3 / 4.如果在A和B列的同一组中C中有任何重复,则应该将其视为最后两行的情况

2 个答案:

答案 0 :(得分:2)

这有点棘手。这是一种方法:

select a, b,
       concat_ws('/',
                 (case when sum(c = 1) > 0 then 1 else '-' end),
                 (case when sum(c = 2) > 0 then 1 else '-' end),
                 (case when sum(c = 3) > 0 then 1 else '-' end),
                 (case when sum(c = 4) > 0 then 1 else '-' end)
                ) as cs
from t
group by a, b

答案 1 :(得分:0)

您可以使用计数表和GROUP_CONCAT

SELECT s.A, s.B,GROUP_CONCAT(COALESCE(m.C, '-') ORDER BY s.n SEPARATOR '/') AS C
FROM mytable m
RIGHT JOIN (
  SELECT A,B, sub.n
  FROM (SELECT DISTINCT A,B FROM mytable) t
  CROSS JOIN (SELECT 1 n  UNION ALL SELECT 2  UNION ALL 
              SELECT 3   UNION ALL SELECT 4  UNION ALL SELECT 5  UNION ALL
              SELECT 6   UNION ALL SELECT 7  UNION ALL SELECT 8  UNION ALL
              SELECT 9   UNION ALL SELECT 10) AS sub) s
  ON m.A = s.A
  AND m.B = s.B
  AND m.C = s.n
WHERE s.n <= (SELECT MAX(C) FROM mytable)
GROUP BY s.A, s.B;

SqlFiddleDemo

输出:

   A       B         C     
 ------- ------- --------- 
  Abc.    Abc.    1/2/3/-  
  Bcd.    Bcd.    -/-/-/4  
  Cde.    Cde.    -/2/-/4  

如果您有更多值,只需增加计数表范围。