将行旋转到列

时间:2017-09-12 20:47:10

标签: sql sql-server reporting-services pivot

我需要创建一个主表来呈现在报表服务中,但我在如何组合数据方面存在问题。 更具体地说,我有一个名为“Reservaciones”的表,它存储了在某些日期保留的住宅信息。

现在,例如,我按以下字段对信息进行分组:

  1. R.ClaTrab AS WorkerId
  2. R.ClaUbicacion AS UbicationID
  3. R.ClaEstancia AS ResidenceID
  4. R.FechaIni AS InitialDay
  5. R.FechaFin AS LastDay
  6. 结果是First result**

    正如您在图片中看到的那样,我们有两行重复,第四行和第五行是准确的。

    到目前为止,这是我的代码

    SELECT  
    R.ClaTrab AS WorkerId,
    MAX(E.NomEstancia) AS ResidenceName, 
    R.ClaUbicacion AS UbicationID, 
    R.ClaEstancia AS ResidenceID, 
    DATEDIFF(DAY, R.FechaIni, R.FechaFin) AS NumberDays, 
    R.FechaIni AS InitialDay,
    R.FechaFin AS LastDay
    FROM Reservaciones AS R
    INNER JOIN Estancias AS E ON E.ClaEstancia = R.ClaEstancia
    WHERE E.ClaUbicacionEst = 3
    GROUP BY  R.ClaTrab,R.ClaUbicacion, R.ClaEstancia, R.FechaIni, R.FechaFin
    ORDER BY R.FechaIni
    

    我希望结果像desire result,但我不知道怎么做,我尝试了PIVOT,但我无法得到我想要的结果。

    如果您需要更多信息,请问我。 非常感谢你。

    解: 我所做的是使用 ROW NUMBER() OVER PARTITION BY 在同一住所创建一组工人,然后 PIVOT 结果在新专栏中。

    SELECT * FROM(
    SELECT  
    MAX(E.NomEstancia) AS ResidenceName,
    R.FechaIni AS InitialDay,
    R.FechaFin AS LastDay,
    DATEDIFF(DAY, R.FechaIni, R.FechaFin) AS NumberDays, 
    T.NomTrab AS Worker,
    R.ClaUbicacion AS UbicationID, 
    R.ClaEstancia AS ResidenceID,
    ROW_NUMBER() OVER(PARTITION BY FechaIni,FechaFin, R.ClaUbicacion, R.ClaEstancia ORDER BY T.NomTrab) AS GUEST
    FROM Reservaciones AS R
    INNER JOIN Estancias AS E ON E.ClaEstancia = R.ClaEstancia
    INNER JOIN Trabajadores AS T ON T.ClaTrab = R.ClaTrab
    WHERE E.ClaUbicacionEst = 3
    GROUP BY T.NomTrab, R.ClaUbicacion, R.ClaEstancia, R.FechaIni,R.FechaFin) AS ONE 
    PIVOT( MAX(Worker) FOR GUEST IN ([1],[2],[3])) AS pvt
    

    在新查询中,我添加了一个新的联接以获取工作人员的姓名

1 个答案:

答案 0 :(得分:0)

由于只能有2名工人,您可以使用最小和最大。

with cte as(
SELECT  
    R.ClaTrab AS WorkerId,
    MAX(E.NomEstancia) AS ResidenceName, 
    R.ClaUbicacion AS UbicationID, 
    R.ClaEstancia AS ResidenceID, 
    DATEDIFF(DAY, R.FechaIni, R.FechaFin) AS NumberDays, 
    R.FechaIni AS InitialDay,
    R.FechaFin AS LastDay
FROM 
    Reservaciones AS R
INNER JOIN 
    Estancias AS E 
    ON E.ClaEstancia = R.ClaEstancia
WHERE 
    E.ClaUbicacionEst = 3
GROUP BY  
    R.ClaTrab,
    R.ClaUbicacion, 
    R.ClaEstancia, 
    R.FechaIni, 
    R.FechaFin),

cte2 as(
select
    ResidenceName
    ,UbicationID
    ,ResidenceID
    ,NumberDays
    ,InitalDay
    ,LastDay
    ,Worker1 = max(WorkerId)
    ,Worker2 = min(WorkerId)
from
    cte
group by
    ResidenceName
    ,UbicationID
    ,ResidenceID
    ,NumberDays
    ,InitalDay
    ,LastDay)

select
    ResidenceName
    ,UbicationID
    ,ResidenceID
    ,NumberDays
    ,InitalDay
    ,LastDay
    ,Worker1
    ,Worker2 = case when Worker1 = Worker2 then NULL else Worker2 end
from
    cte2

<强> ONLINE DEMO WITH PARTIAL TEST DATA