2014-10-02 42 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和窗口函數。