生成有趣的数据视图

时间:2014-07-09 09:09:17

标签: sql sql-server

我有一张表格,其中有我的资源每周活动的记录如下;

Asset Name | Project | Week Beginning | Monday | Tuesday| Wednesday| Thursday| Friday| Saturday | Sunday

James   Project 1   26-06-2014  0   1   1   0   1   0   0
James   Project 1   03-07-2014  1   1   0   1   0   0   0
Dave    Project 3   03-07-2014  1   1   0   1   0   0   0

我需要看詹姆斯,当他开始并完成他的项目时。

所以我需要一个如下所示的视图

Asset Name | Project | Start Date on Project | End Date on Project| Number of days worked 
James       Project 1   27-06-2014  06-07-2014      6
Dave        Project 3   03-07-2014  06-07-2-14      3   

所以我在想一个case语句,游标或带有基于集合的逻辑的存储过程。我想找出最好的和 这样做的最快方法。那么任何想法如何快速生成这个视图?因为昨晚的一个晚上大脑冻结,所以如果有人能激励我,我会非常感激。

3 个答案:

答案 0 :(得分:2)

首先,使用unpivot规范化您的数据,并将天数转换为实际日期。

select AssetName, Project,
 dateadd(d, CASE dayname                    
                    WHEN 'Monday' THEN 0
                    WHEN 'Tuesday' THEN 1
                    WHEN 'Wednesday' THEN 2
                    WHEN 'Thursday' THEN 3
                    WHEN 'Friday' THEN 4
                    WHEN 'Saturday' THEN 5
                    When 'sunday' then 6
end,WeekBeginning) workdate
from
(                    
    select * from yourdata
    unpivot (dayvalue for dayname in (monday,tuesday,wednesday,thursday,friday,saturday,sunday)) u
) v

从那里,这是一个查找最早和最新记录的简单案例。

答案 1 :(得分:2)

SELECT  assetName, project,
        MIN(DATEADD(d, first, weekBeginning)) AS startDate,
        MAX(DATEADD(d, last, weekBeginning)) AS endDate,
        SUM(days) AS daysWorked
FROM    mytable
CROSS APPLY
        (
        SELECT  SUM(d), MIN(n), MAX(n)
        FROM    (
                SELECT  monday, 0
                UNION ALL
                SELECT  tuesday, 1
                UNION ALL
                SELECT  wednesday, 2
                UNION ALL
                SELECT  thursday, 3
                UNION ALL
                SELECT  friday, 4
                UNION ALL
                SELECT  saturday, 5
                UNION ALL
                SELECT  sunday, 6
                ) w (d, n)
        ) q (days, first, last)
GROUP BY
        assetName, project

答案 2 :(得分:1)

试试这个

SELECT ASSETNAME,PROJECT,MIN(T.MIN)START_DAY,MAX(T.MAX) END_DAY,
       DATEDIFF(DD,MIN(t.min) ,MAX(T.MAX)) DURATION
FROM
(
SELECT  ASSETNAME,PROJECT,DATEADD(DD,MIN(WEEK),WEEKBEGINNING) 'MIN',DATEADD(DD,MAX(WEEK),WEEKBEGINNING) 'MAX'
FROM #TEMP  T
CROSS APPLY(SELECT 0 'WEEK' WHERE T.MONDAY=1 UNION ALL SELECT 1 WHERE T.TUESDAY=1 UNION ALL
            SELECT 2 WHERE T.WEDNESDAY=1 UNION ALL SELECT 3 WHERE T.THURSDAY=1 UNION ALL
            SELECT 4 WHERE T.FRIDAY=1 UNION ALL SELECT 5 WHERE T.SATURDAY=1 UNION ALL
            SELECT 6 WHERE T.SUNDAY=1 
            ) D
GROUP BY ASSETNAME,PROJECT,WEEKBEGINNING
)T