【问题标题】:How to get value as string in SQL Server如何在 SQL Server 中将值作为字符串获取
【发布时间】:2018-06-05 05:43:46
【问题描述】:

我有一张桌子tbl_Marks

Std_id  | sub_id  |  term_I   | term_2
--------+---------+-----------+-------
std_1   | 1       |   40      | 50
std_1   | 2       |   30      | 40
std_1   | 3       |   20      | 30
std_1   | 4       |   10      | 50

std_2   | 1       |   50      | 50
std_2   | 2       |   50      | 50
std_2   | 3       |   50      | 50
std_2   | 4       |   50      | 50

我怎样才能得到这样的结果:

Std_id  | sub_id  |  term_I   | term_2 | total  | status | PROMOTION_status
--------+---------+-----------+--------+--------+--------+------------------
std_1   | 1       |   40      | 50     | 90     | PASS   | REPEATER
std_1   | 2       |   30      | 40     | 70     | PASS   | REPEATER
std_1   | 3       |   20      | 20     | 40     | FAIL   | REPEATER
std_1   | 4       |   10      | 50     | 60     | PASS   | REPEATER

注意:如果总价值小于任何 sub_id 的 50

std_2   | 1       |   50      | 50     | 100    | PASS   | PROMOTED
std_2   | 2       |   50      | 50     | 100    | PASS   | PROMOTED
std_2   | 3       |   50      | 50     | 100    | PASS   | PROMOTED
std_2   | 4       |   50      | 50     | 100    | PASS   | PROMOTED

注意:如果总值大于50或等于每个sub_id

请帮忙!

【问题讨论】:

    标签: sql sql-server-2008 sql-server-2012 sql-server-2008-r2


    【解决方案1】:

    使用CASE

     select t.*,
            t.term_I + t.term_2 as total,
            case when t.term_I + t.term_2 >= 50 then 'pass' else 'fail' end as status,
            case when t.std_id = 'std_2' then 'PRMOTED' else 'REAPEATER' end as promotion_status
     from tbl_marks t
    

    【讨论】:

    • std_id有两种,一种属于repeater,另一种属于promotion...同时执行查询值返回repeater的两个std_id
    • @NityanandVishwakarma 立即查看
    • 抱歉打扰了...万一std_id大于50,那么Id应该怎么做呢?请不要介意..因为 Std_Id 将超过 50....
    【解决方案2】:

    以下 SQL Select 语句可以提供帮助 除了SQL CTE expression,您还可以使用子选择语句 但是这个查询的主要技巧是使用MIN aggregation function with Partition by 子句 这可以帮助您检查该学生的分数是否低于 50,如果是,则将该学生的所有记录设为 REPEATER 状态

    ;with cte as (
    select  
    *, 
    term_1 + term_2 as total
    from tbl_Marks
    )
    select
    *,
    case when (term_1 + term_2) >= 50 then 'PASS' else 'FAIL' end as status,
    case when (
    min(total) over (partition by Std_id)
    ) >= 50 then 'PROMOTED' else 'REPEATER' end as PROMOTION_status
    from cte
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2013-04-07
      • 2012-02-09
      • 1970-01-01
      • 1970-01-01
      • 2015-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多