TSQL如何按文字分组?

时间:2013-06-11 15:23:30

标签: sql-server tsql group-by

我将这个问题简化为一个非常简单的形式:

SELECT
'A' AS [Literal]
UNION 
SELECT
'B' AS [Literal]
GROUP BY
[Literal]

我收到消息:

  

Msg 207,Level 16,State 1,Line 7   列名称“文字”无效。

我尝试了同样的结果:

SELECT
t.literal FROM 
(SELECT 'A' AS [Literal]) t
UNION 
SELECT
'B' 
GROUP BY
[Literal]

2 个答案:

答案 0 :(得分:6)

如果您想要GROUP BY UNION

,则需要派生表格
SELECT X.[Literal], [Count] = COUNT(*)
FROM(
    SELECT [Literal] = 'A'
    UNION ALL 
    SELECT [Literal] = 'B'
) X
GROUP BY X.[Literal]

Demo

答案 1 :(得分:1)

你可以使用cte ...

;WITH cte AS (
 SELECT
 'A' AS [Literal]
 UNION 
 SELECT
 'B' AS [Literal])
SELECT [Literal]
FROM cte
GROUP BY [Literal]