SQL group by和cross apply

时间:2016-11-08 16:13:40

标签: sql sql-server aggregate-functions

  id |    systemName | Systemid      
-------------------------------  
  100 |   A100  |       1  
  100 |   B100  |       2  
  100 |   C100  |       3  
  100 |   D100  |       4  
  200 |   A100  |       1  
  200 |   B200  |       2  

达到以下结果的最佳方法是什么?列系统名称应具有计数系统的逗号分隔值

id       Systemidcount   SystemName  
 ---------------------------------------------  
 100  |    4  |            A100,B100,C100,D100  
 200  |    2  |           A100,B200  

由于某种原因,我无法正确格式化,道歉

3 个答案:

答案 0 :(得分:2)

您可能会注意到子查询别名A.这是为了防止在CROSS APPLY

中进行冗余调用
Declare @YourTable table (id int,systemname varchar(25),systemid int)
Insert Into @YourTable values 
(100,'A100',1),
(100,'B100',2),
(100,'C100',3),
(100,'D100',4),
(200,'A100',1),
(200,'B200',2)

Select A.*
      ,SystemName = B.Value
 From  (Select ID,Systemidcount = count(*) From @YourTable Group By ID) A
 Cross Apply (
               Select Value=Stuff((Select Distinct ',' + systemname 
                      From  @YourTable 
                      Where ID=A.ID 
                      For XML Path ('')),1,1,'') 

             ) B
 Order By ID

返回

ID  Systemidcount   SystemName
100 4               A100,B100,C100,D100
200 2               A100,B200

答案 1 :(得分:1)

这是字符串聚合:

<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>

<div id="well">
  <header>
    <h1>Wikipedia Viewer</h1>
  </header>

  <body>
    <br>
    <div id="select">
      <h5><a href="https://en.wikipedia.org/wiki/Special:Random" title="Random Wikipedia Article" target="_blank">Click for a random article</a></h5>
      <br>
      <form>
        <input type="text" id="term" name="search" placeholder="What article?">
        <button id="search">Search</button>
      </form>
      <br>
      <h5>Or search above for a specific one</h5>
    </div>
    <ul id="results">
    </ul>
  </body>
</div>

答案 2 :(得分:1)

SELECTid,COUNT(Systemid) as SystemidCount,
SystemName=Stuff((SELECT ',' + SystemName FROM t t1 WHERE t1.id=t.id
 FOR XML PATH (''))
             , 1, 1, '' )
FROM t
GROUP BY id