SQL Pivot时间表矩阵

时间:2015-10-15 09:22:37

标签: sql sql-server

为了深入了解车辆租赁与车辆占用/空闲时间,我想创建一个时间矩阵(用于SSAS Cube)。

在租赁部分的可用数据下方:

enter image description here

现在我想将此数据转换为以下结果。显示每小时车辆租赁的分钟数。

enter image description here

有关正确的SQL语法的任何帮助都可以实现这一结果。

2 个答案:

答案 0 :(得分:3)

我认为您可以使用CTE 24小时收集并使用;WITH HoursAll(H) AS ( SELECT 0 UNION ALL SELECT H + 1 FROM HoursAll WHERE H < 23 ) SELECT t.date, t.vehicle, CAST((CAST(ha.H As varchar(10)) + ':00') As time) as [hour] , CASE WHEN ha.H = DATEPART(HOUR,t.starttime) THEN 60 - DATEPART(MINUTE,t.starttime) WHEN ha.H = DATEPART(HOUR,t.endtime) THEN DATEPART(MINUTE,t.endtime) ELSE 60 END FROM HoursAll ha JOIN yourTable t ON ha.H BETWEEN DATEPART(HOUR,t.starttime) AND DATEPART(HOUR,t.endtime); 来达到预期效果:

{% block content %}
    <script type="text/javascript" src='/static/media/js/group_sharer.js'></script>
    <form action="." method="POST" id="my-form">
        {% csrf_token %}
        <select name="campaign" id="">
            {% for campaign in campaigns %}
                <option value="{{campaign.id}}">{{campaign.title}}</option>
            {% endfor %}
            <option value="test">test</option>
        </select>
        <input type="submit">
    </form>
{% endblock content %}

答案 1 :(得分:0)

CREATE FUNCTION [dbo].GetTime (@Start TIME, @End TIME)
RETURNS @TableTime TABLE(_HH TIME, _MM INT)
AS
BEGIN
   WHILE DATEPART(HH, @Start) <= DATEPART(HH, @End)
   BEGIN
      INSERT INTO @TableTime
      SELECT DATEPART(HH, @Start), 60
      SET @Start = CAST(DATEADD(HH,1,@Start) AS TIME)
   END
   UPDATE @TableTime SET _MM = 60 - DATEPART(MINUTE, @Start) WHERE _HH = DATEPART(HH, @Start)
   UPDATE @TableTime SET _MM = DATEPART(MINUTE, @End) WHERE _HH = DATEPART(HH, @End)
END


SELECT DATE, VEHICLE CROSS APPLY GetTime(Starttime, Endtime) G