尝试在SQL Server中获取小计

8hhllhi2  于 2023-01-01  发布在  SQL Server
关注(0)|答案(1)|浏览(156)

我正在尝试使用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

eqqqjvef

eqqqjvef1#

您可以通过创建一个列来进行排序,从而根据需要将小计强制添加到结果中。在本示例中,我将UNION查询放入CTE中。我在两个SELECT中添加了一个名为CompanySortColumn的列。在主SELECT中,我按CompanyID、添加的CompanySortColumnOrderID以及您想要的任何顺序对结果进行排序。

WITH prelim as (
  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,  
    1 as CompanySortColumn  --Added column to force desired sort order with subtotals interjected at the "end" of each Company.
  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 ,
    2 as CompanySortColumn  --Added column to force desired sort order with subtotals interjected at the "end" of each Company.
  from
    timesheets TSV
  where 
    CompanyId in ('000000001', '000000002')     
  group by 
    companyid
)
  SELECT *
  FROM prelim
  ORDER BY CompanyID, CompanySortColumn, OrderID

相关问题