# SQL Pivot基于一列的Max

##### 问题描述投票：0回答：2

``````CustomerNM FacilityAccountID Metric Expected DeployTime
-------------------------------------------------------
1                  1           1       1         1
1                  1           1      .5        .5
1                  1           2       2         2
1                  1           2       1         1
1                  1           3       2         2
1                  1           3       3         3
2                  1           1       10        15
2                  1           1       26        17
2                  1           2       25        29
2                  1           2       15        34
2                  1           3       21        7
2                  1           3       33        2
``````

``````SELECT
CustomerNM, FacilityAccountID,
MAX(DeployTime) OVER (Partition BY CustomerNM, FacilityAccountID) as DeployTime,
[1] AS Expected1,
[2] AS Expected2,
[3] AS Expected3
FROM
(SELECT
CustomerNM, FacilityAccountID, metric, expected, DeployTime
FROM
TABLE) p
PIVOT
(SUM (expected)
FOR metric IN ([1], [2], [3])
) AS p
``````

``````CustomerNM FacilityAccountID Expected1  Expected2  Expected3
-----------------------------------------------------------
1               1             1           2         3
2               1            26          15        21
``````
sql pivot max
##### 2个回答
0

``````SELECT CustomerNM, FacilityAccountID,
MAX(CASE WHEN metric = 1 THEN expected END) as expected1,
MAX(CASE WHEN metric = 2 THEN expected END) as expected2,
MAX(CASE WHEN metric = 3 THEN expected END) as expected3
FROM TABLE p
GROUP BY CustomerNM, FacilityAccountID;
``````

0

``````SELECT CustomerNM, FacilityAccountID,
MAX([1]) AS Expected1, MAX([2]) AS Expected2, MAX([3]) AS Expected3
FROM
(SELECT CustomerNM, FacilityAccountID, metric, expected, DeployTime
FROM TABLE t
WHERE DeployTime =
(SELECT MAX(DeployTime)
FROM TABLE t2
WHERE t.CustomerNM = t2.CustomerNM
AND t.metric = t2.metric
AND t.FacilityAccountID = t2.FacilityAccountID)) p
PIVOT
(
SUM (expected)
FOR metric IN
( [1], [2], [3])
) AS p
GROUP BY CustomerNM, FacilityAccountID
``````

``````SELECT CustomerNM, FacilityAccountID,
MAX(CASE WHEN metric = 1 THEN expected END) as expected1,
MAX(CASE WHEN metric = 2 THEN expected END) as expected2,
MAX(CASE WHEN metric = 3 THEN expected END) as expected3
FROM TABLE t
WHERE DeployTime =
(SELECT MAX(DeployTime)
FROM TABLE t t2
WHERE t.CustomerNM = t2.CustomerNM
AND t.metric = t2.metric
AND t.FacilityAccountID = t2.FacilityAccountID)
GROUP BY CustomerNM, FacilityAccountID;
``````