我有一个产生以下结果的查询:
表1:
degree_code occupation_code degree_completions degree_level
1.0000 20-2021 10 1
1.0000 20-2022 10 1
1.1051 52-2095 2 3
1.1051 52-2095 41 2
1.5010 15-1100 2 3
我有另一个小的查找表,它将degree_level与我需要使用的自定义类别联系起来:
表2
degree_level degree_level_recode
1 AADEGREE
2 AADEGREE
3 BACHDEGREE
我想构建第一个查询的输出以报告以下格式:
degree_code occupation_code degree_completions degree_level AADEGREE BACHDEGREE
1.0000 20-2021 10 1 10 0
1.0000 20-2022 10 1 10 0
1.1051 52-2095 2 3 3 0
1.1051 52-2095 41 2 0 41
1.5010 15-1100 2 3 2 1
基本上,在原始查询中创建新的临时重新编码字段,当它们与degree_level_recode匹配时报告它们下面的degree_completions,如果不匹配则输入0。这是高度简化的;我将针对查询中每个元素中的其他字段对recode字段执行操作。
我已经展示了degree_completions字段以供参考,但出于明显的冗余原因,我会在最终查询中将其遗漏。
我认为我需要使用CASE语句或类似的东西进行比较检查,但我是SQL的新手。
修改
参考下面的Cha的答案,采取修改后的table1输出(映射重新编码后):
degree_code degree_level degree_completions degree_level_recode
01.0601 2 11 LESSCOLL
01.0601 3 22 AADEGR
01.0605 2 3 LESSCOLL
考虑这段代码(table2在编辑上方引用):
SELECT degree_code
,degree_level
,[LESSCOL] AS LESSCOL
,[AADEGR] AS AADEGR
,[BACHDEGR] AS BACHDEGR
,[MADEGR] AS MADEGR
,[DOCDEGR] AS DOCDEGR
FROM
(
SELECT degree_code
,table1.degree_level
,degree_level_recode
,degree_code
FROM table1
,table2
WHERE table1.degree_level = table2.degree_code
) AS p
PIVOT
(
SUM (degree_completions)
FOR degree_level_recode IN ([LESSCOL], [AADEGR], . . .)
) AS pvt
产生这些结果:
degree_code degree_level LESSCOL AADEGR BACHDEGR MADEGR DOCDEG
01.0601 2 NULL NULL NULL NULL NULL
01.0601 3 NULL 22 NULL NULL NULL
01.0505 2 NULL NULL NULL NULL NULL
我想去:
degree_code degree_level LESSCOL AADEGR BACHDEGR MADEGR DOCDEG
01.0601 2 11 NULL NULL NULL NULL
01.0601 3 NULL 22 NULL NULL NULL
01.0505 2 3 NULL NULL NULL NULL
此外,将NULL替换为0。
答案 0 :(得分:1)
这就是你所追求的(假设:你的第一个表叫做#temp1,你的第二个表称为#temp2):
SELECT *
FROM
#temp1,
(SELECT degree_level, [AADEGREE] as col1, [BACHDEGREE] as col2
FROM
(SELECT degree_completions, #temp1.degree_level, degree_level_recode
FROM #temp1, #temp2 WHERE #temp1.degree_level = #temp2.degree_level) AS p
PIVOT
(
SUM (degree_completions)
FOR degree_level_recode IN
([AADEGREE], [BACHDEGREE])
) AS pvt
) as V
WHERE #temp1.degree_level = V.degree_level
ORDER BY 1