我有一张表MonitorLocationDetails
,如下所示
lid LoclColumn LocDescription
1 MP1 MP-1 descr
2 MP2 MP-2 descr
3 MainGate Main Gate descr
我应该获取LocDescription
的行并将其转换为sql server其他版本中的pivot。 PIVOT在sql紧凑版本中不可用。
透视应该基于子查询的结果
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
你能帮忙吗?
答案 0 :(得分:0)
你关闭了。您只需将MAX
放在CASE expression
。
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')