我正在尝试加入两个表并使用CASE语句但是,我没有得到我想要的结果。
这是我现有的代码:
SELECT i.[ProviderID], l.FacilityName,
CASE WHEN [StepID] = 1 THEN 'Step0.5' END AS 'Step0.5',
CASE WHEN [StepID] = 2 THEN 'StepI' END AS 'StepI',
CASE WHEN [StepID] = 4 THEN 'StepI.D' END AS 'StepI.D',
CASE WHEN [StepID] = 5 THEN 'StepII.1' END AS 'StepII.1',
CASE WHEN [StepID] = 6 THEN 'StepII.5' END AS 'StepII.5',
CASE WHEN [StepID] = 7 THEN 'StepII.D' END AS 'StepII.D',
CASE WHEN [StepID] = 8 THEN 'StepIII.1' END AS 'StepIII.1'
FROM RD.dbo.vwProvider as l
INNER JOIN [RD].[dbo].[vwSteps] i
ON l.ProviderID = i.ProviderID
Group by i.[ProviderID], l.FacilityName, [StepID]
ORDER BY FacilityName
以下是我目前的结果:
ProviderID FacilityName Step0.5 StepI StepI.D StepII.1 StepII.5 StepII.D StepIII.1
4 This Is Us Step0.5 NULL NULL NULL NULL NULL NULL
4 This Is Us NULL NULL StepI.D NULL NULL NULL NULL
6 Almost NULL NULL NULL StepII.1 NULL NULL NULL
6 Almost NULL NULL NULL NULL NULL StepII.D NULL
6 Almost NULL StepI NULL NULL NULL NULL NULL
以下是我要找的结果:
ProviderID FacilityName Step0.5 StepI StepI.D StepII.1 StepII.5 StepII.D StepIII.1
4 This Is Us Step0.5 NULL StepI.D NULL NULL NULL NULL
6 Almost NULL StepI NULL StepII.1 NULL StepII.D NULL
答案 0 :(得分:1)
您需要从StepId
中删除GROUP BY
并引入聚合函数:
SELECT i.[ProviderID], l.FacilityName,
MAX(CASE WHEN [StepID] = 1 THEN 'Step0.5') END AS 'Step0.5',
MAX(CASE WHEN [StepID] = 2 THEN 'StepI' END) AS 'StepI',
MAX(CASE WHEN [StepID] = 4 THEN 'StepI.D' END) AS 'StepI.D',
MAX(CASE WHEN [StepID] = 5 THEN 'StepII.1' END) AS 'StepII.1',
MAX(CASE WHEN [StepID] = 6 THEN 'StepII.5' END) AS 'StepII.5',
MAX(CASE WHEN [StepID] = 7 THEN 'StepII.D' END) AS 'StepII.D',
MAX(CASE WHEN [StepID] = 8 THEN 'StepIII.1' END) AS 'StepIII.1'
FROM RD.dbo.vwProvider l INNER JOIN
[RD].[dbo].[vwSteps] i
ON l.ProviderID = i.ProviderID
Group by i.[ProviderID], l.FacilityName
ORDER BY FacilityName
答案 1 :(得分:0)
使用MAX()
或MIN()
进行汇总,看起来您StepID
中不需要GROUP BY
:
SELECT i.[ProviderID], l.FacilityName,
max(CASE WHEN [StepID] = 1 THEN 'Step0.5' END) AS 'Step0.5',
max(CASE WHEN [StepID] = 2 THEN 'StepI' END) AS 'StepI',
max(CASE WHEN [StepID] = 4 THEN 'StepI.D' END) AS 'StepI.D',
max(CASE WHEN [StepID] = 5 THEN 'StepII.1' END) AS 'StepII.1',
max(CASE WHEN [StepID] = 6 THEN 'StepII.5' END) AS 'StepII.5',
max(CASE WHEN [StepID] = 7 THEN 'StepII.D' END) AS 'StepII.D',
max(CASE WHEN [StepID] = 8 THEN 'StepIII.1' END) AS 'StepIII.1'
FROM RD.dbo.vwProvider as l INNER JOIN [RD].[dbo].[vwSteps] i ON l.ProviderID = i.ProviderID
Group by i.[ProviderID], l.FacilityName
ORDER BY FacilityName