你这个不用行转列啊,就是求最大值最小值
------------------------------------------------------------------------------
WITH T1 AS (
SELECT 'a' AS LX, '2023-04' AS SJ , 5 AS SZ
UNION ALL
SELECT 'a' AS LX, '2023-05' AS SJ , 40 AS SZ
UNION ALL
SELECT 'a' AS LX, '2023-07' AS SJ , 10 AS SZ
UNION ALL
SELECT 'b' AS LX, '2023-06' AS SJ , 20 AS SZ
UNION ALL
SELECT 'b' AS LX, '2023-07' AS SJ , 10 AS SZ
UNION ALL
SELECT 'b' AS LX, '2023-09' AS SJ , 30 AS SZ
)
SELECT
LX,
MIN(SJ) AS MIN_SJ,
MAX(SJ) AS MAX_SJ,
MIN(SZ) AS MIN_SZ,
MAX(SZ) AS MAX_SZ
FROM
T1
GROUP BY LX
---------------------------------------------------------------------------------
WITH T1 AS (
SELECT 'a' AS LX, '2023-04' AS SJ , 5 AS SZ
UNION ALL
SELECT 'a' AS LX, '2023-05' AS SJ , 40 AS SZ
UNION ALL
SELECT 'a' AS LX, '2023-07' AS SJ , 10 AS SZ
UNION ALL
SELECT 'b' AS LX, '2023-06' AS SJ , 20 AS SZ
UNION ALL
SELECT 'b' AS LX, '2023-07' AS SJ , 10 AS SZ
UNION ALL
SELECT 'b' AS LX, '2023-09' AS SJ , 30 AS SZ
),T2 AS (
SELECT
LX,
-- MIN(SJ) AS MIN_SJ,
-- MAX(SJ) AS MAX_SJ,
MIN(SZ) AS MIN_SZ,
MAX(SZ) AS MAX_SZ
FROM
T1
GROUP BY LX
)
SELECT
T2.LX,
MIN(T2.MIN_SZ) AS MIN_SZ,
MAX(T2.MAX_SZ) AS MAX_SZ,
MIN(T1.SJ) AS MIN_SJ,
MAX(T1.SJ) AS MAX_SJ
FROM T1
RIGHT JOIN T2 ON T1.LX = T2.LX AND (T2.MIN_SZ = T1.SZ OR T2.MAX_SZ = T1.SZ)
GROUP BY T2.LX