多个列在sql中逐个行并计算这些值

时间:2014-12-22 09:07:18

标签: sql-server-2008

User  |  Acc1 | Acc2 |  Acc3 |  Acc4
_____________________________________    
1     |  BB   |  B   |    CC |   AA    
1     |  AA   | CC   |    B  |       
1     |  BB   | CC   |    AA |

期望的输出:

User | Acc |  Count    
1    | BB  |  2    
1    | B   |  2    
1    | AA  |  3    
1    | CC  |  3

我想查询我的输出

1 个答案:

答案 0 :(得分:1)

select user, acc, sum(cnt) as count
from
(
    select user, acc1 as acc, count(*) as cnt from your_table group by acc1
    union all
    select user, acc2, count(*) from your_table group by acc2
    union all
    select user, acc3, count(*) from your_table group by acc3
    union all
    select user, acc4, count(*) from your_table group by acc4
) tmp
group by user, acc