有一个表“OBJECTS”,其中一列“OBJECT_NAME”具有三个值OBJ1,OBJ2,OBJ3。 表OBJECTS的快照是:
OBJECT_NAME
----------
OBJ3
OBJ1
OBJ2
OBJ1
OBJ1
OBJ2
如何编写有效的SQL查询以获取输出格式的不同对象的计数,如下所示。
OBJ1_Count OBJ2_COUNT OBJ3_COUNT
---------------------------------
3 2 1
答案 0 :(得分:3)
试试这个:
select
sum(case when [object_name] = 'OBJ1' then 1 else 0 end) as obj1_count,
sum(case when [object_name] = 'OBJ2' then 1 else 0 end) as obj2_count,
sum(case when [object_name] = 'OBJ3' then 1 else 0 end) as obj3_count
from
[objects]
object_name上的索引肯定是有益的
答案 1 :(得分:0)
您可以使用数据透视表:
SELECT * FROM [OBJECTS]
PIVOT (COUNT([OBJECT_NAME])
FOR [OBJECT_NAME] IN ([OBJ1],[OBJ2],[OBJ3])) AS [OBJCount]
如果您不想对列名进行硬编码,可以使用动态sql获取它们。
DECLARE @cols AS NVARCHAR(MAX)
, @query AS NVARCHAR(MAX)
SET @cols = STUFF((SELECT DISTINCT
',' + QUOTENAME(o.[OBJECT_NAME])
FROM [OBJECTS] o
FOR XML PATH('')
, TYPE
).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
SET @query = 'SELECT * FROM [OBJECTS]
PIVOT (COUNT([OBJECT_NAME])
FOR [OBJECT_NAME] IN (' + @cols + ')) AS [OBJCount]'
EXECUTE(@query)