TSQL数据库问题

时间:2014-12-14 00:25:41

标签: sql-server tsql pivot

您好我有一个临时表(@tempResult),其中包含以下结果......

-----------------------------------------
| DrugAliasID | Dosage1 | Unit1 | rowID | 
-----------------------------------------
| 322         | 10      | MG    | 1     |
| 322         | 50      | ML    | 2     |
| 441         | 20      | ML    | 3     |
| 443         | 15      | ML    | 4     |
-----------------------------------------

我希望结果如下所示,转动具有相同DrugAliasID的行。

--------------------------------------------------
| DrugAliasID | Dosage1 | Unit1 | Dosage2 | Unit2 |
--------------------------------------------------
| 322         | 10      | MG    | 50      | ML    |
| 441         | 20      | ML    | NULL    | NULL  |
| 443         | 15      | ML    | NULL    | NULL  |
--------------------------------------------------

到目前为止,我有一个不使用数据透视的解决方案。我对枢轴不太好,并且想知道在这种情况下是否有人知道如何使用它。或者以其他方式解决它。感谢

SELECT  
    tr.drugAliasID, 
    MIN(trmin.dosage1) AS dosage1,
    MIN(trmin.unit1) AS unit1,
    MIN(trmax.dosage1) AS dosage2,
    MIN(trmax.unit1) AS unit2
FROM 
    @tempResult tr
JOIN 
    @tempResult trmin ON trmin.RowID = tr.rowid AND trmin.drugAliasID = tr.drugAliasID
JOIN 
    @tempResult trmax ON trmax.RowID = tr.rowid AND trmax.drugAliasID = tr.drugAliasID
JOIN 
    (SELECT 
         MIN(RowID) AS rowid,
         drugAliasID 
     FROM 
         @tempResult 
     GROUP BY 
         drugAliasID) tr1 ON tr1.rowid = trmin.RowID
JOIN 
    (SELECT 
         MAX(RowID) AS rowid,
         drugAliasID 
     FROM 
         @tempResult 
     GROUP BY 
         drugAliasID) tr2 ON tr2.rowid = tr.RowID
GROUP BY 
    tr.drugAliasID
HAVING 
    count(tr.drugAliasID) > 1

1 个答案:

答案 0 :(得分:1)

假设您的SQL Server版本支持使用CTE,您可以简化查询:

;with cte as
(select *, row_number() over (partition by drugaliasid order by rowid) rn
 from @tempResult
)

select c.drugaliasid, c.dosage1, c.unit1, c2.dosage1 as dosage2, c2.unit1 as unit2
from cte c
left join cte c2 on c.drugaliasid = c2.drugaliasid and c.rn = 1 and c2.rn = 2
where c.rn = 1

Demo

这将为您提供所需的结果,而无需使用pivot关键字。