在 SQL 精简版子查询的 transposed/pivoted 结果中将结果显示为 1 行

display result as 1 row in transposed/pivoted result of sub query in SQL Compact edition

我有一个 table MonitorLocationDetails 如下所示

lid LoclColumn  LocDescription
1   MP1         MP-1 descr
2   MP2         MP-2 descr
3   MainGate    Main Gate descr 

我应该获取 LocDescription 的行并像在 sql 服务器其他版本中的 pivot 一样转置它。 PIVOT 在 sql 精简版中不可用。 Pivoting 应该基于子查询的结果

SELECT LocColumn,LocDescription 
FROM MonitorLocationDetails 
WHERE LocColumn IN ('MP1','MP2','MainGate')

这工作正常。

我到目前为止:

SELECT DISTINCT 
    (CASE WHEN P.LocColumn = 'MP1' THEN P.LocDescription ELSE '' END), 
    (CASE WHEN P.LocColumn = 'MainGate' THEN P.LocDescription ELSE '' END), 
    (CASE WHEN P.LocColumn = 'MP2' THEN P.LocDescription ELSE '' END) 
FROM (
    SELECT LocColumn,LocDescription 
    FROM MonitorLocationDetails 
    WHERE LocColumn IN ('MP1','MP2','MainGate')
) P

产生:

column1     column2     column3
                        MP-2 descr
            Main Gate desc  
MP-1 descr      

即使使用了 DISTINCT 也有空格..我没有给列命名,因为我需要 1 行中的结果如下

MP-1 descr   Main Gate descr    MP-2 descr

请问有人帮忙吗?

你很接近。您只需在 CASE expression.

之前添加 MAX
SELECT 
    MAX(CASE WHEN P.LocColumn = 'MP1' THEN P.LocDescription ELSE '' END), 
    MAX(CASE WHEN P.LocColumn = 'MainGate' THEN P.LocDescription ELSE '' END), 
    MAX(CASE WHEN P.LocColumn = 'MP2' THEN P.LocDescription ELSE '' END) 
FROM (
    SELECT LocColumn,LocDescription 
    FROM MonitorLocationDetails 
    WHERE LocColumn IN ('MP1','MP2','MainGate')
) P

您还可以简化查询:

;WITH MonitorLocationDetails(lid, LocColumn, LocDescription) AS(
    SELECT 1, 'MP1', 'MP-1 Descr' UNION ALL
    SELECT 2, 'MP2', 'MP-2 Descr' UNION ALL
    SELECT 3, 'MainGate', 'MainGate Descr'
)
SELECT
    MAX(CASE WHEN LocColumn = 'MP1' THEN LocDescription ELSE '' END), 
    MAX(CASE WHEN LocColumn = 'MainGate' THEN LocDescription ELSE '' END), 
    MAX(CASE WHEN LocColumn = 'MP2' THEN LocDescription ELSE '' END) 
FROM MonitorLocationDetails 
WHERE LocColumn IN ('MP1','MP2','MainGate')