我正在尝试使用union在SQL Server中获取小计,并且我能够获取小计,但我希望在companyID
的末尾获取它。现在我处于中间位置,而不是公司的末尾。想知道是否有人知道我如何在CompanyID
的末尾获取小计。
select distinct
Personid,
concat(rtrim(LastName),+ ', ',+ rtrim(FirstName)) as PersonName,
CompanyName, CompanyId, OrderId, JobTitle,
cast(TSPayRate as varchar) as PayRate,
cast(TSBillRate as varchar) as BillRate,
cast(RegHours as varchar) as TotalRegHours,
cast(OTHours as varchar) as TotalOTHours
from
timesheets TSV
where
CompanyId in ('000000001', '000000002')
--group by Personid, Concat(rtrim(LastName),+ ', ',+ rtrim(FirstName)), CompanyName, CompanyId, orderid,JobTitle, PayRate, BillRate, reghours, othours
union all
select distinct
' ', ' ', ' ', companyid, ' ', ' ', ' ',
cast('SUBTOTAL' as varchar),
sum(RegHours) as TotalRegHours,
sum(OTHours) as TotalOTHours
from
timesheets TSV
where
CompanyId in ('000000001', '000000002')
group by
companyid
order by
companyid
1条答案
按热度按时间eqqqjvef1#
您可以通过创建一个列来进行排序,从而根据需要将小计强制添加到结果中。在本示例中,我将
UNION
查询放入CTE中。我在两个SELECT
中添加了一个名为CompanySortColumn
的列。在主SELECT
中,我按CompanyID
、添加的CompanySortColumn
、OrderID
以及您想要的任何顺序对结果进行排序。