2

次のテーブルとデータがあります

DutyRoaster:

╔═══════════════╦═════════════════════════╦═════════╦════════════╗
║  DutyRecordId ║        DutyDate         ║ ShiftNo ║ EmployeeId ║
╠═══════════════╬═════════════════════════╬═════════╬════════════╣
║             1 ║ 2013-09-10 00:00:00.000 ║       1 ║          2 ║
║             2 ║ 2013-09-10 00:00:00.000 ║       1 ║         10 ║
║             3 ║ 2013-09-10 00:00:00.000 ║       2 ║          7 ║
║             4 ║ 2013-09-10 00:00:00.000 ║       2 ║          9 ║
║             5 ║ 2013-09-10 00:00:00.000 ║       2 ║          4 ║
║             6 ║ 2013-09-10 00:00:00.000 ║       3 ║         12 ║
║             7 ║ 2013-09-10 00:00:00.000 ║       3 ║          5 ║
║             8 ║ 2013-09-10 00:00:00.000 ║       4 ║          3 ║
║             9 ║ 2013-09-10 00:00:00.000 ║       4 ║          1 ║
║            10 ║ 2013-09-10 00:00:00.000 ║       4 ║         13 ║
╚═══════════════╩═════════════════════════╩═════════╩════════════╝

別のテーブルがemplyeedIdあり、Name
次のような結果が必要です。

╔══════════════════════════════════════════════════════╗
║  Date        Shiftno1  Shiftno 2   Sitno 3 Shiftno4  ║
╠══════════════════════════════════════════════════════╣
║                                                      ║
║     10-02-1203  Jhon      peter       Micheal  Jim   ║
║                 Smith     Molly       Henry    Kim   ║
║                           Adam                 Nick  ║
║                                                Kaity ║
╚══════════════════════════════════════════════════════╝

Pivot を使用してこれを取得することは可能ですか?

4

2 に答える 2

0

SQL Server (または PostgreSQL) の場合、これを行うことができます。

with cte as (
    select
        d.DutyDate,
        d.ShiftNo,
        e.Name, 
        row_number() over(partition by d.ShiftNo order by d.DutyRecordId) as rn
    from DutyRoaster as d
        inner join Employees as e on e.Id = d.EmployeeId
)
select
    case when c.rn = 1 then c.DutyDate end as DutyDate,
    min(case when c.ShiftNo = 1 then c.Name end) as ShiftNo1,
    min(case when c.ShiftNo = 2 then c.Name end) as ShiftNo2,
    min(case when c.ShiftNo = 3 then c.Name end) as ShiftNo3,
    min(case when c.ShiftNo = 4 then c.Name end) as ShiftNo4
from cte as c
group by c.DutyDate, c.rn
order by c.DutyDate, c.rn

sql fiddle demo

于 2013-09-10T10:13:29.287 に答える