用于转换逻辑的SQL查询

时间:2017-10-16 17:06:20

标签: sql sql-server

输入:

表1:

Col1 Col2
1    ABC
2    XYZ
3    PQR
4    ASD
5    QWE

表2:

Col1 col2
ABC  .35
ABC  .65
XYZ   .3
XYZ   .3
XYZ   .4
PQR   .2
PQR   .4
PQR   .3
PQR   .1
QWE    1

输出:

Col1  pct1 pct2 pct3 pct4
 1     .35  .65  0    0
 2     .3   .3   .4   0
 3     .2   .4   .3   .1
 4      1    0   0    0
 5      1    0   0    0

如何在SQL Server中实现这一点?

1 个答案:

答案 0 :(得分:3)

您可以使用PIVOT,但首先必须使用ROW_NUMBER()对每个组的行进行排名:

WITH Ranked
AS
(

    SELECT
      t1.Col1,
      t2.Col2,
      ROW_NUMBER() OVER(PARTITION BY t1.Col2 ORDER BY t1.Col2)  AS RN
    FROM Table1 AS t1
    LEFT JOIN Table2 AS t2 ON t1.Col2 = t2.Col1

)
SELECT Col1, 
  COALESCE([1], 0) AS pct1, 
  COALESCE([2], 0) AS pct2, 
  COALESCE([3], 0) AS pct3, 
  COALESCE([4], 0) AS pct4
FROM Ranked AS r
PIVOT
(
   MAX(Col2)
   FOR RN IN([1], [2], [3], [4])
) AS p;

结果:

| Col1 | pct1 | pct2 | pct3 | pct4 |
|------|------|------|------|------|
|    1 | 0.35 | 0.65 |    0 |    0 |
|    2 |  0.3 |  0.3 |  0.4 |    0 |
|    3 |  0.2 |  0.4 |  0.3 |  0.1 |
|    4 |    0 |    0 |    0 |    0 |
|    5 |    1 |    0 |    0 |    0 |