SQL Server 2016 Enterprise,使用SSMS ...
我有一个查询:
WITH SUMS AS (
SELECT
dbo.BillingActivity.BillingCodeId AS [Billing Code],
dbo.Clients.ClientName AS [Client Name],
dbo.BillingCodes.Name AS [Billing Code Name]
, SUM(CASE WHEN Details LIKE '%"LW":"True"%' THEN 1 ELSE 0 END) AS [LW]
, SUM(CASE WHEN Details LIKE '%"MHN":"True"%' THEN 1 ELSE 0 END) AS [MHN]
, SUM(CASE WHEN Details LIKE '%"EPAP":true%' THEN 1 ELSE 0 END) AS [EPAP]
, SUM(CASE WHEN Details LIKE '%"EPAP (old)":"True"%' THEN 1 ELSE 0 END) AS [EPAPOld]
FROM dbo.BillingActivity
INNER JOIN dbo.BillingCodes ON dbo.BillingActivity.BillingCodeId=dbo.BillingCodes.Id
INNER JOIN dbo.Clients ON dbo.BillingActivity.ClientId=dbo.Clients.ID
WHERE dbo.BillingActivity.RecordDateTime BETWEEN '2017-11-09' AND '2017-11-10'
GROUP BY dbo.BillingActivity.BillingCodeId, dbo.BillingCodes.Name, dbo.Clients.ClientName)
SELECT
[Billing Code],
[Client Name],
[Billing Code Name],
[LW],
[MHN],
[EPAP],
[EPAPOld],
SUM(LW+MHN+EPAP+EPAPOld) OVER (PARTITION BY [Billing Code Name]) AS [Billing Code Total]
FROM SUMS
ORDER BY [Client Name] ASC, [Billing Code Name] ASC
这给了我以下结果:(该表拒绝在此处正确排列,因此图像:
我想知道是否可能(到目前为止互联网研究会说不),我是否可以添加此查询以创建第9列,该列将显示“帐单代码总计”列中所有金额的总和。它显示在哪一行并不重要,如果在所有行中显示相同的数量也不重要,我只需要在某处看到该列的总和。
请注意,“结算代码总计”名称是别名。这提出了另一项挑战。
非常感谢。
答案 0 :(得分:1)
您不需要billing code total
的{{1}}条款,但您可以使用其他列,例如:
WITH
sums AS (
SELECT
dbo.BillingActivity.BillingCodeId AS [billing code]
, dbo.Clients.ClientName AS [client name]
, dbo.BillingCodes.Name AS [billing code name]
, SUM(CASE WHEN Details LIKE '%"LW":"True"%' THEN 1 ELSE 0 END) AS [lw]
, SUM(CASE WHEN Details LIKE '%"MHN":"True"%' THEN 1 ELSE 0 END) AS [mhn]
, SUM(CASE WHEN Details LIKE '%"EPAP":true%' THEN 1 ELSE 0 END) AS [epap]
, SUM(CASE WHEN Details LIKE '%"EPAP (old)":"True"%' THEN 1 ELSE 0 END) AS [epapold]
FROM dbo.BillingActivity
INNER JOIN dbo.BillingCodes ON dbo.BillingActivity.BillingCodeId = dbo.BillingCodes.Id
INNER JOIN dbo.Clients ON dbo.BillingActivity.ClientId = dbo.Clients.ID
WHERE dbo.BillingActivity.RecordDateTime BETWEEN '2017-11-09' AND '2017-11-10'
GROUP BY
dbo.BillingActivity.BillingCodeId
, dbo.BillingCodes.Name
, dbo.Clients.ClientName
)
SELECT
[Billing Code]
, [Client Name]
, [Billing Code Name]
, [LW]
, [MHN]
, [EPAP]
, [EPAPOld]
, LW + MHN + EPAP + EPAPOld AS [billing code total]
, SUM(LW + MHN + EPAP + EPAPOld) OVER() as all_sum
FROM sums
ORDER BY
[Client Name] ASC
, [Billing Code Name] ASC