2013-10-16 214 views
0

我知道我想做什麼,但我正在努力尋找最好的方法來做到這一點。合併查詢結果

我有一個回我一些數據的查詢:

SELECT 
[Description] As [Name], month([OccuredOn]) as [Month], year([OccuredOn]) AS [Year],  COUNT([id]) AS Cnt 
FROM MyTable 
GROUP BY [Description], Year([OccuredOn]), Month([OccuredOn]) 
ORDER BY [Description],Year([OccuredOn]), month([OccuredOn]) 

的問題是我需要一些結果合併成一個。

以下是我想要做的,但我需要能夠將string1和string2的記錄合併到一個單一的string3記錄中。

SELECT 
CASE [Description] 
    WHEN 'String1' THEN 'String3' 
    WHEN 'String2' THEN 'String3' 
    ELSE [Description] 
END As [Name], 
month([OccuredOn]) as [Month], year([OccuredOn]) AS [Year], COUNT([id]) AS Cnt 
FROM MyTable 
GROUP BY [Description], Year([OccuredOn]), Month([OccuredOn]) 
ORDER BY [Description],Year([OccuredOn]), month([OccuredOn]) 

我知道上面是不是要做到這一點,但希望有人能指出一個方法可以讓我回到我的結果,其中有字符串1或字符串2回報作爲一個單一的唯一的行那天有任何說明累計計數。

上面的SQL顯然返回兩批數據的字符串1和字符串

感謝

+0

你試過用[[名稱]而不是用[[說明]組進行分組]嗎? – PlantTheIdea

+0

我想你應該看看SELECT DISTINCT而不是GROUP BY – rheitzman

回答

1

你傳播你的casegroup byorder by條款

SELECT 
CASE [Description] 
    WHEN 'String1' THEN 'String3' 
    WHEN 'String2' THEN 'String3' 
    ELSE [Description] 
END As [Name], 
month([OccuredOn]) as [Month], year([OccuredOn]) AS [Year], COUNT([id]) AS Cnt 
FROM MyTable 
GROUP BY CASE [Description] 
    WHEN 'String1' THEN 'String3' 
    WHEN 'String2' THEN 'String3' 
    ELSE [Description] 
END, Year([OccuredOn]), Month([OccuredOn]) 
ORDER BY CASE [Description] 
    WHEN 'String1' THEN 'String3' 
    WHEN 'String2' THEN 'String3' 
    ELSE [Description] 
END,Year([OccuredOn]), month([OccuredOn]) 
+0

完美!這正是我之後的事情。非常感謝。 – JIbber4568

+0

我真的很希望他的桌子不是那麼大。羣體和訂單中的情況說明是非常不友好的 – PlantTheIdea

+0

@PlantTheIdea:那麼,有沒有更好的方法? – geomagas

0

你能做到這一點?

SELECT * 
FROM (SELECT 
     CASE [Description] 
     WHEN 'String1' THEN 'String3' 
     ELSE [Description] 
     END As [Name], 
     month([OccuredOn]) as [Month], year([OccuredOn]) AS [Year], COUNT([id]) AS Cnt 
     FROM MyTable 
     UNION 
     SELECT 
     CASE [Description] 
     WHEN 'String2' THEN 'String3' 
     ELSE [Description] 
     END As [Name], 
     month([OccuredOn]) as [Month], year([OccuredOn]) AS [Year], COUNT([id]) AS Cnt 
     FROM MyTable) 
GROUP BY [Description], Year([OccuredOn]), Month([OccuredOn]) 
ORDER BY [Description],Year([OccuredOn]), month([OccuredOn]) 
+0

如果你走這個方向,推薦使用'UNION ALL'而不是'UNION'。你的分組處理唯一性,不需要通過'UNION'驗證它。 – PlantTheIdea