2008-10-24 27 views
1

確定:這是我的一些表結構的事項這裏在T-SQL骨材困惑

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

他想輸出標題,如果沒有重複。如果表格中有重複的標題,他想顯示OverrideTitle(這是我的猜測)。 – splattne 2008-10-24 10:46:12

回答

1

將取代具有相應overrideTitle值出現多次的每個標題。

它會保持它的第一次出現,例如,如果你有3個冠軍就好了,一個,一個只有第二和第三個將被替換

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 

如果你想只需更換所有的人改變> <>如下

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 
1

你可以實現它,而無需使用tempory表是這樣的:

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

我不知道你是否需要原表的每一行。因此,這裏是我的替代解決方案,讓你的每一行:

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