SQL新手(确实是新手),需要添加总行数

时间:2019-04-11 15:01:49

标签: sql sql-server

我正在尝试为最近几个月的工作写一个快速查询,我要显示所有需要的行,现在我想添加一条总行。

DECLARE @fee DECIMAL(10, 2);
SET @fee = 99.79;

SELECT   
    t.jobnum, t.veh AS 'VEH', 
    CONVERT(VARCHAR, t.IssueDate, 1) AS 'ISS.DATE', 
    CONVERT(VARCHAR, t.CreatedDate, 1) AS 'ENT.DATE', 
    t.Id AS 'ID', 
    @fee AS 'FEE'
FROM
    dbo.jobs AS t
WHERE 
    t.CreatedDate >= DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) - 1, 0) 
    AND t.CreatedDate < DATEADD(mm, DATEDIFF(mm, 0, GETDATE()), 0)

我现在想在底部添加以下内容:

TOTAL JOBS XXXX   (xxxx - this would be a count of records)
FEE PER JOB: @fee
TOTAL FEE: XXXX.XX   (xxxx.xx - THIS IS the total jobs * @fee)

1 个答案:

答案 0 :(得分:0)

是下一个结果集的底部?

您可以将查询结果转储到临时表中,然后从该表中进行选择+创建另一个包含附加信息的结果集:

declare @fee decimal(10, 2);
set @fee = 99.79;

SELECT t.jobnum, t.veh AS 'VEH', convert(varchar, t.IssueDate, 1) AS 
'ISS.DATE', convert(varchar, t.CreatedDate, 1) AS 'ENT.DATE', t.Id AS 
'ID', @fee AS 'FEE'
INTO #jobs
FROM dbo.jobs as t
WHERE t.CreatedDate >= DATEADD(mm,DATEDIFF(mm,0,GETDATE())-1,0) AND 
    t.CreatedDate < DATEADD(mm,DATEDIFF(mm,0,GETDATE()),0)

-- this will be your first resultset, the one you already have
SELECT * FROM #jobs

-- this will create another result set, with additional information
SELECT COUNT(*) TotalJobs
     , @fee AS FeePerJob
     , @fee * COUNT(*) AS TotalFee
  FROM #jobs