合并查询的结果

时间:2013-10-16 14:58:52

标签: sql sql-server-2008 merge case

我知道我想做什么,但我很难找到最好的方法。

我有一个回复给我一些数据的查询:

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])

我知道以上不是这样做的方法,但希望有人可以指出一种方法我可以返回我的结果,其中任何带有string1或string2的描述作为该日期的单个唯一行返回累计计数。

上面的SQL显然会为string1和string2

返回两个数据

由于

2 个答案:

答案 0 :(得分:1)

您必须将case传播到group 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])

答案 1 :(得分: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])