如何根据计数获得百分比

时间:2017-07-10 09:31:01

标签: sql sql-server tsql

我有一个样本表

ID  Name    today_cnt   yesterday_cnt
1   mohan     10020        10080
1   mohan      1200        10080

如何获得计数差异的百分比值

1)10080-10020 = 60 = 5%> 记录数量的微小差异

2)10080-1200 = 8800 = 90%>> 记录数量的巨大差异

输出

ID  Name    today_cnt   yesterday_cnt  Percentage
1   mohan    10020          10080         5%
1   mohan    1200           10080      80%

4 个答案:

答案 0 :(得分:2)

不确定你的' 5%',但是像这样

    declare @t table (ID int,  Name varchar(100),   today_cnt int,  yesterday_cnt int);
    insert into @t values
    (1,   'mohan',     10020,       10080),
    (1,   'mohan',      1200,       10080),
    (1,   'mohan',      10090,       10080)


    select *, 
           yesterday_cnt - today_cnt as diff,
           case when yesterday_cnt > today_cnt 
                then cast(round ((yesterday_cnt - today_cnt) *1. / yesterday_cnt * 100, 2) as decimal(3,1)) 
                else 0
           end as [%]
    from @t

答案 1 :(得分:1)

SELECT ID, Name, today_cnt, yesterday_cnt, 
       ROUND((yesterday_cnt-today_cnt)/yesterday_cnt*100) AS Percentage
FROM TABLE;

这样的东西? 我不建议连接'%'%但是,如果要将Percentage列用作输入。

答案 2 :(得分:0)

$query = YourEntityQuery::create('e')
    ->withColumn('e.sortColumn IS NULL', 'isSortColumnNull')
    ->orderBy('isSortColumnNull', 'desc')
    ->orderBy('e.sortColumn', 'desc');

希望这就是你要找的......

答案 3 :(得分:0)

select查询将是这样的

SELECT s.id AS id, Name, 
case when yesterday_count > today_count
then cast(round ((yesterday_count - today_count) / yesterday_count * 100, 2) as decimal(3,0)) else 5 end as 'increment'
FROM users_students AS s

点击此处SQLFiddle