将多个查询结果分组到一列中

时间:2013-04-11 15:43:18

标签: sql-server-2008 drop-down-menu

是否可以使用子查询执行查询并在第一个查询的一列(DropDownList style)内获取子查询结果?

Select Name, Year, (Select SchoolId from Schools) from SchoolRecords

Output :

--------------------------      List would be a DropDownList and if I open it I would get
| Name | Year | SchoolId |      the results of my subquery like so :
|      |      |          | 
--------------------------      ------------------
| Jim  | 2011 | List  || |      |             || |
|      |      |       \/ |      |             \/ |
--------------------------      ------------------
| Tom  | 2012 | List  || |      |    012312324   |
|      |      |       \/ |      |    123245465   |
--------------------------      |    456547787   | 
                                ------------------

1 个答案:

答案 0 :(得分:1)

无法在SQL中创建值的下拉列表。但如果您只想要学校列中的学校列表,那么您可以使用FOR XML PATH获取列表:

Select Name, 
  Year, 
  STUFF((SELECT distinct ', ' + cast(s.SchoolId as varchar(10))
         from Schools s
         FOR XML PATH(''), TYPE
         ).value('.', 'NVARCHAR(MAX)') 
        ,1,2,'') schools
from SchoolRecords

请参阅SQL Fiddle with Demo

然后,如果您有一个表格,将每个SchoolRecords与特定的school相关联,那么您只能显示与每个用户相关联的学校:

Select Name, 
  Year, 
  STUFF((SELECT distinct ', ' + cast(s.SchoolId as varchar(10))
         from Schools s
         inner join record_school rs
           on rs.schoolid = s.schoolid
         where r.id = rs.id
         FOR XML PATH(''), TYPE
         ).value('.', 'NVARCHAR(MAX)') 
        ,1,2,'') schools
from SchoolRecords r;

请参阅SQL Fiddle with Demo