用于显示基于Name的数据的SQL查询

时间:2017-03-28 08:29:06

标签: sql sql-server

我正在创建一个SQL查询。我的表格如下: -

DECLARE @Tab TABLE
(
    Name VARCHAR(10), 
    NUM INT,
    PracticeName VARCHAR(10)
)

INSERT INTO @Tab 
VALUES ('A', 25, 'Test'), ('B', 30, 'Test'), ('C', 236, 'Test1'),
       ('D', 217, 'Test'), ('E', 19, 'Test1')

我使用的查询是:

 SELECT 
     PracticeName,
     'Total:' + CAST(SUM(NUM) as varchar(10)) + ' ('+   
                STUFF((SELECT ', ' + Name + ':' + CAST(NUM as varchar(10))  
                       FROM @Tab  
                       FOR XML PATH('')), 1, 1, '') +')'  
 FROM @Tab  
 GROUP BY PracticeName

我得到的输出是:

Test    Total:272 ( A:25, B:30, C:236, D:217, E:19)
Test1   Total:255 ( A:25, B:30, C:236, D:217, E:19)

我希望输出为: -

Test      Total:272 ( A:25, B:30, D:217)
Test1     Total:255 (C:236, E:19)

请帮忙

1 个答案:

答案 0 :(得分:1)

只需在stuff()

上添加SELECT PracticeName,'Total:' + CAST(SUM(NUM) as varchar(10)) +' ('+ STUFF( ( SELECT ', ' + s.Name +':'+ CAST(s.NUM as varchar(10)) FROM @Tab s WHERE s.PracticeName = m.PracticeName FOR XML PATH('') ), 1, 1, '') +')' FROM @Tab m GROUP BY PracticeName 条款即可
<div-c>
 <center>
  <divs></div>
 </center>
</div-c>