I have a table MonitorLocationDetails
which looks like below
lid LoclColumn LocDescription
1 MP1 MP-1 descr
2 MP2 MP-2 descr
3 MainGate Main Gate descr
I should get the rows of LocDescription
and transpose it like pivot in sql server other versions. PIVOT not available in sql compact versions.
The Pivoting should be based on the result of a sub query
SELECT LocColumn,LocDescription
FROM MonitorLocationDetails
WHERE LocColumn IN ('MP1','MP2','MainGate')
This works ok.
I have so far :
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
which yields:
column1 column2 column3
MP-2 descr
Main Gate desc
MP-1 descr
empty spaces even with DISTINCT used.. i did not give names for columns, cause i need the result just as follows in 1 row
MP-1 descr Main Gate descr MP-2 descr
Any one would you please assist?
You're close. You just have to put MAX
before your 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
You could also simplify your query:
;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')