SQL我需要帮助来计算dateiff的百分比形式

时间:2017-11-23 12:42:57

标签: mysql sql database rdbms

My table
room_name    |   datecount | percentage
Room1A       |   7         |
Room2A       |   3         |
Room3A       |   2         |
Room5B       |   1         |

SELECT r.room_name,datediff(b.dateout,f.datein) as datecount
FROM room r INNER JOIN form f ON r.room_name=f.room_name INNER JOIN bill b 
ON f.ID=b.Form_ID 
GROUP BY r.room_name

我想计算百分比 所以[Room1A | 7 | 54%]

4 个答案:

答案 0 :(得分:0)

我想使用窗口函数

SELECT room_name, datecount,
       datecount * 100 / SUM(datecount) OVER(ORDER BY (SELECT 1)) [percentage]
FROM (Subquery) t;

答案 1 :(得分:0)

您可以使用交叉联接获取总数

  SELECT  r.room_name, sum(datediff(b.dateout,f.datein)) as datecount
      , sum((datediff(b.dateout,f.datein))/tot)*100 as percentage
  FROM room r 
  CROSS JOIN  (
      select sum(datediff(b.dateout,f.datein)) as  tot
      from room
  ) t
  GROUP BY r.room_name

答案 2 :(得分:0)

我认为您想要的查询如下所示:

SELECT r.room_name, SUM(datediff(b.dateout, f.datein)) as datecount,
       SUM(datediff(b.dateout, f.datein)) / fb.sumdiff
FROM room r INNER JOIN 
     form f
     ON r.room_name = f.room_name INNER JOIN
     bill b 
     ON f.ID = b.Form_ID CROSS JOIN
     (SELECT SUM(datediff(b.dateout, f.datein) as sumdiff
      FROM form f JOIN
           bill b
           ON f.ID = b.Form_ID
     ) fb
GROUP BY r.room_name, fb.sumdiff;

请注意外部查询中的SUM()。您的版本为每个房间返回任意差异。我最好的猜测是你想要每个房间的日期总和。

答案 3 :(得分:0)

我会用这样的东西

SELECT *, (datecount * 100 / (SELECT CAST(SUM(datecount) AS DECIMAL) FROM @Table)) 
AS perc
FROM @Table
GROUP BY room_name, datecount