是否可以使用子查询执行查询并在第一个查询的一列(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 |
------------------
答案 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
然后,如果您有一个表格,将每个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;