sql - Grouping sub query in one row -


 clientid  amount     flag mmc          600     1   mmc          700     1 fdn          800     1 fdn          350     2 fdn          700     1 

using sql server,below query getting 2 rows fro fdn. combine client values in 1 row. output should like

 client  gtcount, totalamountgreaterthan500  lscount,amountlessthan500 mmc  2  1300               0        0 fdn  2      1500               1        350  
select      f.clientid,f.flag,     case when flag = 1 count(*) end gtcount,     sum(case when flag = 1 amount end) totalamountgreaterthan500, case when flag = 2 count(*) end lscount,     sum(case when flag = 2 amount end) amountlessthan500,     ( select clientid, amount,flag #mytable)f group clientid,f.flag 

try

select clientid,            sum(case when flag = 1 1 else 0 end) gtcount,        sum(case when flag = 1 amount else 0 end) totalamountgreaterthan500,        sum(case when flag = 2 1 else 0 end) lscount,        sum(case when flag = 2 amount else 0 end) amountlessthan500   table1  group clientid 

output:

 | clientid | gtcount | totalamountgreaterthan500 | lscount | amountlessthan500 | |----------|---------|---------------------------|---------|-------------------| |      fdn |       2 |                      1500 |       1 |               350 | |      mmc |       2 |                      1300 |       0 |                 0 | 

here sqlfiddle demo


Comments

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

java.util.scanner - How to read and add only numbers to array from a text file -

iphone - Three second countdown in cocos2d -