0

是否可以使用子查询进行查询并在第一个查询的一列 ( 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   | 
                                ------------------
4

1 回答 1

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

然后,如果您有一个将每个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

于 2013-04-11T17:10:45.610 回答