【问题标题】:spliting one column to three columns in sql在sql中将一列拆分为三列
【发布时间】:2014-10-02 04:37:13
【问题描述】:

我有一张桌子

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 

【问题讨论】:

  • 这背后的逻辑是什么?第一个表是如何转换成结果的??给定name = 'sam'test = 'test1' - 你如何找出“通过计数”或“失败计数”?您需要提供更多信息 - 而不仅仅是一堆数据行!
  • 想出新列的值的魔法是什么?

标签: sql-server


【解决方案1】:

好吧,花了一点时间才意识到列标题有点误导

/**
    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 和 test 5 之间的额外空格是错字吗? 还有其他有用的构造:CTE 和窗口函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-10
    • 1970-01-01
    相关资源
    最近更新 更多