有没有办法在不使用pivot和unpivot方法的情况下在sql中显示水平数据?下图是使用pivot和unpivot的示例,但我想知道还有其他方法吗?
+----+-------+-----------------+
| id | Place | Location |
+----+-------+-----------------+
| 1 | CP01 | 3.1415,101.7231 |
| 2 | CP02 | 3.2314,101.3254 |
| 3 | CP03 | 3.9415,101.0192 |
| 4 | CP04 | 3.5490,102.0435 |
| 5 | CP05 | 3.2562,101.2597 |
| 6 | CP06 | 3.1134,102.5915 |
+----+-------+-----------------+
+----------+-----------------+-----------------+-----------------+-----+
| Cols | 1 | 2 | 3 | ... |
+----------+-----------------+-----------------+-----------------+-----+
| Location | 3.1415,101.7231 | 3.2314,101.3254 | 3.9415,101.0192 | ... |
| Place | CP01 | CP02 | CP03 | ... |
+----------+-----------------+-----------------+-----------------+-----+
答案 0 :(得分:0)
类似的方法是你可以使用交叉应用和一些条件聚合来实现pivot
和unpivot
方式
SELECT a.Col1, MAX(case when a.ID = 1 then a.Value end) [1],
MAX(case when a.ID = 2 then a.Value end) [2],
MAX(case when a.ID = 3 then a.Value end) [3]
FROM table T
CROSS APPLY (VALUES ('Place', T.place, T.ID),
('Location', T.Location, T.ID)
) as a(Col1, Value, ID)
group by a.Col1
答案 1 :(得分:0)
你可能会寻找这样的东西:
DECLARE @GeoData TABLE (Id INT, Place VARCHAR(10), [Location] VARCHAR(100))
INSERT INTO @GeoData
SELECT 1,'CP01','3.1415,101.7231'
UNION ALL
SELECT 2,'CP02','3.2314,101.3254'
SELECT 'Location' AS Cols,
MAX(CASE WHEN t.Id = 1 THEN t.Location END) AS [1],
MAX(CASE WHEN t.Id = 2 THEN t.Location END) AS [2],
MAX(CASE WHEN t.Id = 2 THEN t.Location END) AS [3]
FROM @GeoData t
UNION ALL
SELECT 'Place' AS Cols,
MAX(CASE WHEN t.Id = 1 THEN t.Place END) AS [1],
MAX(CASE WHEN t.Id = 2 THEN t.Place END) AS [2],
MAX(CASE WHEN t.Id = 2 THEN t.Place END) AS [3]
FROM @GeoData t