丑陋的表查询

时间:2015-11-19 15:52:02

标签: sql-server tsql

我继承了这个表并尝试优化查询。我坚持一个查询。这是表格信息

  • RaterName - varchar(24) - 评估者的姓名
  • TimeTaken - varchar(12) - 存储为00:10:14:8
  • 年 - char(4) - 存储为2014

我需要

  1. 不同的评分者列表,评分者总数,评分人员sum(TimeTaken),评估者avg(timetaken)(特定年份)

  2. 我还需要sum(timetaken)avg(TimeTaken)所有评估者(特定年份)

  3. 以下是我为#1提出的查询...我希望总和和avg像hh:mm:ss。我怎么能这样做?

    SELECT 
          [RaterName]
          , count(*) as TotalRatings
          , SUM((DATEPART(hh,convert(datetime, timetaken, 101))*60)+DATEPART(mi,convert(datetime, timetaken, 101))+(DATEPART(ss,convert(datetime, timetaken, 101))/(60.0)))/60.0  as TotalTimeTaken
          , AVG((DATEPART(hh,convert(datetime, timetaken, 101))*60)+DATEPART(mi,convert(datetime, timetaken, 101))+(DATEPART(ss,convert(datetime, timetaken, 101))/(60.0)))/60.0  as AverageTimeTaken
      FROM 
          [dbo].[rating]
      WHERE 
          year = '2014'
      GROUP BY 
          RaterName
      ORDER BY 
          RaterName
    

    输出:

    RaterName   TotalRatings    TotalTimeTaken  AverageTimeTaken
    ================================================================
    Rater1          257     21.113609   0.082154
    Rater2          747     41.546106   0.055617
    Rater3          767     59.257218   0.077258
    Rater4          581     37.154163   0.063948
    

    我可以在此查询中加入#2,还是编写第二个查询并从中删除组?

    在前端,我正在使用C#。

1 个答案:

答案 0 :(得分:2)

    WITH  data ( raterName, timeTaken )
            AS (
                 SELECT raterName,
                        DATEDIFF(MILLISECOND, CAST('00:00' AS TIME),
                                 CAST(timeTaken AS TIME))
                 FROM   rating
                 WHERE  CAST([year] AS INT) = 2014
               )
      SELECT  raterName, COUNT(*) AS totalRatings,
              SUM(timeTaken) AS totalTimeTaken, avg(timeTaken) AS averageTimeTaken
FROM data
      GROUP BY raterName
      ORDER BY raterName;

PS:如果你不想要毫秒,可以制作秒或分钟。 编辑:在您的C#前端,您可以将毫秒或秒写入TimeSpan,这将为您提供使用ToString时的格式。即:

var ttt = TimeSpan.FromSeconds(totalTimeTaken).ToString();