2014-10-02 85 views
-4

我有一个表劈裂一列到三列SQL

name  test  count 
---------------------------- 
sam  test1  10 
sam  test2   2 
sam  passcount  5 
riz  test4   3 
riz  test5   4 
riz  passxount  6 

我想要显示的结果

name    test    pass count   fail count     total count 
------------------------------------------------------------------- 
sam    test1     7     10        17 
sam    test2    15      2        17 
riz    test 4    10      3 
riz    test 5    9      4         13 
+3

这背后的逻辑是什么?第一个表格如何转换为结果?鉴于'name ='sam''和'test ='test1'' - 你如何找出“通过次数”或“失败次数”?您需要提供更多信息 - 不仅仅是一堆数据行! – 2014-10-02 05:24:23

+2

想出新的列的值是什么_magic_? – melancia 2014-10-02 05:24:35

回答

0

好花的一点点时间来实现列标题稍微missleading

/** 
    pass = total for name minus that for current test 
    fail = total count for that test in src table 
    total = total count for that name 
*/ 

select 
    t1.name, 
    t1.test, 
    t2.total-t1.count as pass_count, 
    t1.count as fail_count, 
    t2.total as total_count 
from Kamrams_table as t1 
inner join 
    (
    select 
     k1.name, 
     sum(k1.count) as total 
    from Kamrams_table as k1 
    group by k1.name 
    ) as t2 
on t1.name = t2.name 
; 

注: 我相信TEST4和测试5之间的额外空间输出表是一个错字?还有其他一些有用的构造:CTE和窗口函数。