【问题标题】:group by conditional on two columns in hibernate对休眠中的两列按条件分组
【发布时间】:2017-05-14 06:12:45
【问题描述】:

我想按两列分组。如果 b 不为空,我想按 a 和 b 获得 c 组的总数,如果 b 为空,我想按 a 组 我写了这个查询,但是如果 b 为空,它就不起作用!查询的结果是所有 b 不为空的行

select  m.s.a ,
case when (m.l is not  null)  
then  m.l.code end , coalesce(sum(m.c),0  ) 
from material m where m.Item.id =:itemId 
group by m.s.a, case 
when (m.l is not null)  
then m.l.code end


+--+----+-------+---+
|  | s  | l     | c |
+--+----+-------+---+
|  |  a | d     |  1 |
|  |  a | d     |  9 |
|  |  a | e     |  3 |
|  |  a | f     |  4 |
|  |  c | g     |  5 |
|  |  c | g     |  6 |
|  |  c | h     | 20 |
|  |  d | null  |  7 |
|  |  d | null  |  8 |

预期结果:

+--+----+-------+---+
|  | s  | l     | c |
+--+----+-------+---+
|  |  a | d     | 10 |
|  |  a | e     |  3 |
|  |  a | f     |  4 |
|  |  c | g     | 11 |
|  |  c | h     | 20 |
|  |  d |       | 15 |

【问题讨论】:

  • 你的问题没有多大意义。请在问题中添加一些示例数据和预期输出以澄清。
  • @GurwinderSingh 在编辑我的帖子并添加示例数据和预期输出

标签: sql oracle hibernate group-by


【解决方案1】:

默认情况下,oracle/postgres/mysql 会产生预期的输出。

SELECT s,l,sum(c)
FROM temp
GROUP BY s,l;

如果您不想按 NULL 值分组,可以使用 UNION

SELECT s,l,sum(c)
FROM temp
WHERE l is NOT NULL
GROUP BY s,l
UNION
SELECT s,l,sum(c)
FROM temp
WHERE l is NULL;

【讨论】:

  • 我尝试了第一个查询,结果和上面一样!
  • 你可以分享示例数据集吗?
【解决方案2】:
with data (col1, col2, val) as
(
  select 'a',   'd',        1 from dual union all  
  select 'a',   'd',        9 from dual union all  
  select 'a',   'e',        3 from dual union all  
  select 'a',   'f',        4 from dual union all  
  select 'c',   'g',        5 from dual union all  
  select 'c',   'g',        6 from dual union all  
  select 'c',   'h',       20 from dual union all  
  select 'd',   null,       7 from dual union all  
  select 'd',   null,       8 from dual union all
  select 'e',   'g',     null from dual  -- additional check if val is null
)
,
prs (col1, col2, col1n2) as 
(
  select distinct col1, col2, col1||'-'||col2 from data
)
,
rs (col, val) as 
(
  -- concatenate the columns that need to be grouped by 
  -- to act as one single column (col1 and col2)
  select col1||'-'||col2, sum(nvl(val,0)) from data group by col1||'-'||col2
)
select 
  prs.col1, prs.col2, rs.val 
from 
  rs join prs 
  on (prs.col1n2 = rs.col)
order by 1
;

【讨论】:

    猜你喜欢
    • 2012-12-21
    • 2018-06-20
    • 1970-01-01
    • 1970-01-01
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-19
    相关资源
    最近更新 更多