0

我正在使用 SQL 报告生成器并希望在周转时间内计算百分比

我的桌子看起来像

Name  count  within tat
jeff   1      1
jeff   1      0
jeff   1      1
jeff   1      0

我希望它看起来像这样。

Name  count  within tat
jeff   4     2 (50%)  

我用来在 tat 内计算的代码是

case
when (convert(Decimal(10,2),
    (cast(datediff(minute,
        (CAST(RequestDate AS DATETIME) + CAST(RequestTime AS DATETIME)), 
    REQUEST_TESTLINES.AuthDateTime)as float)/60/24))) > 
    EXP_TAT then '1' else '0' end as [withintat]

我怎样才能总结这一列?

4

4 回答 4

0

你在找这样的东西吗?

select name , sum(count) total, sum(within_tat)*100 /sum(count) as percent

from Table1
Group by name

看演示 SQLFIDDLE

编辑。

或者,如果你想要它,你想试试这个

 select name , sum(count) as total, CONCAT(sum(within_tat),' ' ,'(',sum(within_tat)*100 /sum(count),  '%',')' ) as percent

from Table1
Group by name

在这里查看演示

于 2013-01-23T18:11:42.183 回答
0

你可以把它包在另一个SELECT.

SELECT SUM(count), SUM(withintat)
FROM (/*Your original query*/)
于 2013-01-23T18:12:11.220 回答
0

是的,您可以在 sum() 中使用 case 语句

但它需要返回一个数字..

你的“in tat”变成了类似的东西

select case when (convert(Decimal(10,2),
                 (cast(datediff(minute,
                 (CAST(RequestDate AS DATETIME) + CAST(RequestTime AS DATETIME)), 
                 REQUEST_TESTLINES.AuthDateTime)as float)/60/24))) > 
                 EXP_TAT 
            then 1 
            else 0 end as [withintat]
        ....

但是,如果您需要总和和百分比。

您将需要使用此值两次。

而且我确定您不想保留复制代码。

所以使用你的实际查询作为子查询来总结它可能是一个好主意......

如果您真的不想将其用作子查询

你应该使用外部应用来收集 intat 的值,做这样的事情

 select Name
       ,count(*) as [count]
       ,sum(OA.[withintat]) as [withintat]
       ,sum(OA.[withintat])*100/count(*) as [percent]
       ,cast(sum(OA.[withintat]) as varchar(max))+' ('+cast(sum(OA.[withintat])*100/count(*) as varchar(max))+' %)' as [withintat_and_percent]
 from your_actual_query
 outer apply(select case when (convert(Decimal(10,2),
                              (cast(datediff(minute,
                              (CAST(RequestDate AS DATETIME) + CAST(RequestTime AS DATETIME)), 
                              REQUEST_TESTLINES.AuthDateTime)as float)/60/24))) > EXP_TAT 
            then 1 
            else 0 end as [withintat]
 )OA
 where ....
于 2013-01-23T18:43:48.490 回答
0

在这种情况下我会使用 an IF(双关语除外)。我试图降低您比较的复杂性,但没有看到一些实际数据,这是一个最好的猜测。

   select 
   name, 
   count(name) as count, 
   concat(
      sum(if(datediff(minute, 
             (cast(RequestDate AS DATETIME) + 
              cast(RequestTime AS DATETIME)),
             REQUEST_TESTLINES.AuthDateTime) / 60 / 24 > EXP_TAT, 1, 0 )),
      ' (',
      format(
         (sum(if(datediff(minute, 
                 (cast(RequestDate AS DATETIME) + 
                  cast(RequestTime AS DATETIME)),
                 REQUEST_TESTLINES.AuthDateTime) / 60 / 24 > EXP_TAT, 1, 0 )        
            )/count(name))*100,1),
      '%)'
   ) as 'within tat'
于 2013-01-23T18:52:52.230 回答