2017-05-14 49 views
0

我想按兩列分組。如果b不爲空,並且如果b爲空,我想得到c的總數a和b 我寫了這個查詢,但它在b爲空的情況下不起作用!查詢的結果是所有的行b是不是空group by hibernate中的兩列有條件

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 | 
+0

你的問題並沒有多大意義。請在問題中添加一些示例數據和預期輸出以進行說明。 – GurV

+0

@GurwinderSingh在編輯我的文章,並添加示例數據和預期的輸出 – faraa

回答

2

默認情況下,ORACLE/Postgres的/ MySQL會產生預期的輸出。

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

如果你不想GROUP BY 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; 
+0

我試過第一個查詢,我得到了與上面相同的結果! – faraa

+1

很高興知道。如果它有幫助,那麼請標記爲已接受並且贊成。 – ansh

+0

謝謝,但我的意思是結果是錯誤的 – faraa

0
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 
;