添加与列数类似的Int列值

时间:2014-08-15 15:56:20

标签: sql sql-server sql-server-2012

我的数据结构类似于:

Person | Counter
Mary       1
Mary       2
John       5
John       6

我正在尝试在Person列上分组依据,并为每个人添加计数器的值。意思是,我想回来:

Person - Mary - Has 3 Counters
Person - John - Has 11 Counters

这是我目前的努力,但不起作用:

SELECT ('Person - '+  ISNULL(NULLIF([Person],''),'NOT ASSIGNED') + 'Has') as Name, 
COUNT(*) Match, (SELECT COUNT(*) + 'Counters' FROM [MyTable] )  Total 
FROM [MyTable]   

5 个答案:

答案 0 :(得分:1)

你想要的是像你所说的一个分组条款,所以基于这个:

SELECT Person, SUM(Counter)
FROM MyTable
GROUP BY Person

我没有包含原始查询中的额外文字,以使其更紧凑。

答案 1 :(得分:1)

你走了:

DECLARE @DATA TABLE (Person VARCHAR(25), [Counter] INT)

INSERT INTO @DATA
SELECT 'Mary',1 UNION
SELECT 'Mary',2 UNION
SELECT 'John',5 UNION
SELECT 'John',6

SELECT 'Person - ' + ISNULL(Person,'Not Assigned') + ' - has ' + CAST(SUM([Counter]) AS VARCHAR) + ' counters'
from @DATA
GROUP BY Person

答案 2 :(得分:0)

你应该使用聚合函数。

SELECT ('Person - '+  ISNULL(NULLIF([Person],''),'NOT ASSIGNED') + 'Has') as Name, 
       COUNT(*) As Match,       
       Sum(Counter) As Count
FROM   [MyTable]   
Group By Person

你在第二行也错过了As。 Sum Aggregate函数将对每个组的所有值求和,在本例中为计数器。

答案 3 :(得分:0)

Cheruvian的回答可能就是你想要的,我不能通过你的例子准确地说出来,以下是我想出的以防万一。

SELECT 'Person - ' + ISNULL(NULLIF(Person, ''), 'NOT ASSIGNED') + ' - Has ' + SUM(Counter) + ' Counters' As ReportOutput
FROM MyTable
GROUP BY Person
ORDER BY Person;

答案 4 :(得分:0)

我会在子选择中使用GROUP BY来执行此操作,然后使用结果构建字符串。像这样:

SELECT ('Person - '+  myperson + ' Has ' + CAST(mycount  AS VARCHAR) + ' Counters')
FROM (SELECT ISNULL(NULLIF([Person],''),'NOT ASSIGNED') myperson, sum(counter) mycount
      FROM [MyTable]
      GROUP BY ISNULL(NULLIF([Person],''),'NOT ASSIGNED')) a