好的:这是我的一些表结构,这里很重要
CaseStudyID int
Title nvarchar(50)
OverrideTitle nvarchar(50)
我的部分程序
Declare @Temp table(CaseStudyID int,
Title nvarchar(50))
Insert Into @Temp
SELECT CaseStudyID,Title
FROM CaseStudy
WHERE Visible = 1 AND DisplayOnHomePage = 1
ORDER BY Title
Update @Temp Set Title = TitleOverride
--Here is where im lost if the title occurs more than once
--I need to replace it with the override
--Schoolboy error or leaking brain I cant get it going
Select * From @Temp
有人可以帮忙吗?
答案 0 :(得分:2)
我不确定你是否需要原始表的每一行。所以这是我的替代解决方案,为您提供每一行:
SELECT CaseStudyID, Title
FROM CaseStudy c1
WHERE NOT EXISTS (
SELECT * FROM CaseStudy c2
WHERE c2.CaseStudyID <> c1.CaseStudyID and c2.Title = c1.Title
)
UNION ALL
SELECT CaseStudyID, OverrideTitle
FROM CaseStudy c1
WHERE exists (
SELECT * FROM CaseStudy c2
WHERE c2.CaseStudyID <> c1.CaseStudyID and c2.Title = c1.Title
)
ORDER BY Title
答案 1 :(得分:1)
你可以在不使用临时表的情况下实现它:
SELECT
MIN(CaseStudyID) AS CaseStudyID,
CASE WHEN count(*) = 1 THEN
MIN(Title)
ELSE
MIN(OverrideTitle)
END AS Title
FROM CaseStudy
GROUP BY Title
ORDER BY Title
答案 2 :(得分:1)
这将替换使用相应的overrideTitle值多次出现的每个标题。
它将保留第一次出现,例如,如果您有3个标题,如a,a,a只有第二个,第三个将被替换
select distinct
cs1.CaseStudyID,
case when cs2.CaseStudyID is null then cs1.Title else cs1.overrideTitle end as title
from
CaseStudy cs1
left join CaseStudy cs2
on cs1.title = cs2.title
and cs1.CaseStudyID > cs2.CaseStudyID
如果您想要替换所有这些,只需更改&gt;到&lt;&gt;如下
select distinct
cs1.CaseStudyID,
case when cs2.CaseStudyID is null then cs1.Title else cs1.overrideTitle end as title
from
CaseStudy cs1
left join CaseStudy cs2
on cs1.title = cs2.title
and cs1.CaseStudyID <> cs2.CaseStudyID