我想实现以下转型:
示例数据
SELECT NumWURm,ReportAText,ReportBText,ReportCText,ReportDText,ReportEText,ReportFText
FROM t_SchFacility
WHERE FacID IN (483,485)
结果:
NumWURm ReportAText ReportBText ReportCText ReportDText ReportEText ReportFText
3 Report On venue Warm Up Photo Get Set
2 Report On venue Warm Up Photo
所需输出
我想让公共列值按原样显示,如果值不同,我想显示一些默认文本。
NumWURm ReportAText ReportBText ReportCText ReportDText ReportEText ReportFText
3 Report On venue Warm Up Photo Default Text
答案 0 :(得分:1)
这就是我最喜欢的MIN = MAX技巧。当MIN和MAX相同时,只有一个值,MIN或MAX可用作THE值。
SELECT
MAX(NumWURm) as NumWURm,
CASE WHEN MIN(ReportAText) = MAX(ReportAText)
THEN MIN(ReportAText)
ELSE 'Default'
END,
CASE WHEN MIN(ReportBText) = MAX(ReportBText)
THEN MIN(ReportBText)
ELSE 'Default'
END,
CASE WHEN MIN(ReportCText) = MAX(ReportCText)
THEN MIN(ReportCText)
ELSE 'Default'
END,
CASE WHEN MIN(ReportDText) = MAX(ReportDText)
THEN MIN(ReportDText)
ELSE 'Default'
END,
CASE WHEN MIN(ReportEText) = MAX(ReportEText)
THEN MIN(ReportEText)
ELSE 'Default'
END,
CASE WHEN MIN(ReportFText) = MAX(ReportFText)
THEN MIN(ReportFText)
ELSE 'Default'
END
FROM t_SchFacility
WHERE FacID IN (483,485)
如果您需要确实特定,则可能需要为字符串比较指定一个排序规则选项(例如,如果案件差异对您很重要)。
答案 1 :(得分:0)
以下将为非空集生成单行输出。
with [Selected] ([NumWURm], [ReportAText], [ReportBText], [ReportCText], [ReportDText], [ReportEText], [ReportFText])
(
select [NumWURm], [ReportAText], [ReportBText], [ReportCText], [ReportDText], [ReportEText], [ReportFText]
from [t_SchFacility]
where [FacID] IN (483, 485)
),
[Number_Selected] ([count])
(
selected count(*)
from [Selected]
),
[ReportAText] ([ReportAText])
(
select s.[ReportAText], n.[count]
from [Selected] as s cross join [Number_Selected] as n
group by s.[ReportAText], n.[count]
having count(*) = n.[count]
),
...
[ReportFText] ([ReportFText])
(
select s.[ReportFText], n.[count]
from [Selected] as s cross join [Number_Selected] as n
group by s.[ReportFText], n.[count]
having count(*) = n.[count]
)
select
max(s.[NumWURm]) as 'NumWuRm',
a.coalesce([ReportAText], 'Default Text') as 'ReportAText',
b.[ReportBText] as 'ReportBText',
c.[ReportCText] as 'ReportCText',
d.[ReportDText] as 'ReportDText',
e.[ReportEText] as 'ReportEText',
f.[ReportFText] as 'ReportFText'
from
[Selected] as s
left outer join
[ReportAText] as a
on (null is null)
left outer join
...
[ReportFText] as f
on (null is null)
这是代码大纲,因此需要进行适当的测试和调整。