我发现很难说出我想要实现的目标.我有一个看起来像这样的表:
user char --------- a | x a | y a | z b | x b | x b | y c | y c | y c | z
如何编写一个可以返回以下结果的查询?
user x y z ------- a |1|1|1| b |2|1|0| c |0|2|1|
数字表示原始表中字符的出现次数
编辑:字符值未知,因此解决方案不能限制在这些值.很抱歉没有提及它.我正在使用Oracle DB,但计划使用JPQL构建查询.
select user, sum(case when char='x' then 1 else 0 end) as x, sum(case when char='y' then 1 else 0 end) as y, sum(case when char='z' then 1 else 0 end) as z from thetable group by user
或者,如果您不介意垂直堆叠,此解决方案将为您提供一个解决方案,即使使用未知字符集也可以使用:
select user, char, count(*) as count from thetable group by user, char
这会给你:
user char count a x 1 a y 1 a z 1 b x 2
如果要将一组未知的值水平排出(如在演示输出中),则需要进入动态查询...... SQL标准不是为了生成具有未知列数的输出而设计的. ..希望这有用!