0

我试图在我的存储过程中加入这两个语句。我该怎么做才能得到一张桌子,这样我就可以使用 groupBy 列。

Select 
  TableA.Name,
  TableB.Occupation,
  'Group1' AS [groupBy]
From
 TableA,
 TableB
Where
 TableA.ID = 1

Select 
  TableA.Name,
  TableB.Occupation,
  'Group2' AS [groupBy]
From
 TableA,
 TableB
Where
 TableB.ID = 10

我的结果应该是这样的

Name    Occupation      GroupBy
David   Doctor          Group1
John    Pilot           Group1
Dwayne  Wrestler        Group2
Axel    RockStar        Group2

更新

Table A

ID Name  Occupation  
1  David Doctor
1  John  Pilot
2  Mike  Clerk


Table B 

ID  Name   Occupation
3   Wayne  Writer
4   Shane  Publisher

10 德韦恩摔跤手 10 阿克塞尔摇滚明星

4

1 回答 1

2

似乎您可以使用 aUNION ALL来获得结果:

Select 
  TableA.Name,
  TableA.Occupation,
  'Group1' AS [groupBy]
From TableA
Where TableA.ID = 1
union all
Select 
  TableB.Name,
  TableB.Occupation,
  'Group2' AS [groupBy]
From TableB
Where TableB.ID = 10

请参阅SQL Fiddle with Demo。AUNION ALL将返回两个查询之间的所有行。如果您认为您可能有要删除的重复项,那么您可以使用UNION.

于 2013-04-08T21:59:04.417 回答