我正在SSRS Report Builder 2016中创建报告。
我有一组数据,其中包含一组代理机构以及每个月向每个代理机构收取的费用金额(总计帐单)。每个代理商可以为TotalBilled设置多个值。我想找到每个代理商的TotalBilled中位数。
我计算了查询中的中位数,但它取自所有代理商中的所有TotalBilled,而不仅仅是与我在参数中设置的代理商相关的TotalBilled。
这是我的数据集查询:
DECLARE @Cnt int = (SELECT COUNT(TotalBilled) FROM InvoiceLine)
select
a.AgencyID
a.startdate,
a.enddate,
[TotalBilled],
((SELECT TOP 1 TotalBilled
FROM (
SELECT TOP (@Cnt/2) TotalBilled
FROM InvoiceLine I
WHERE TotalBilled is NOT NULL
ORDER BY TotalBilled ASC
) AS I
ORDER BY TotalBilled DESC) +
(
SELECT TOP 1 TotalBilled
FROM (
SELECT TOP (@Cnt/2) TotalBilled
FROM InvoiceLine I
WHERE TotalBilled is NOT NULL
ORDER BY TotalBilled DESC
) AS I
ORDER BY TotalBilled ASC)) / 2 AS MedianTotalBilled
from Agency a
left join invoiceLine invl
on a.InvoiceID = invl.InvoiceID
where (a.agencyid in (@agency))
and (a.startdate >= @startdate and a.enddate <= @enddate)
更改meidan值计算以使其受我的参数影响而不仅仅是从整个数据库中提取的正确方法是什么?
编辑:
也将联接添加到中位数calc中并没有带来中位数的预期值。这是我目前正在尝试的方法:
(SELECT TOP 1 TotalBilled
FROM (
SELECT TOP (@Cnt/2) TotalBilled
left join invoiceLine invl
on a.InvoiceID = invl.InvoiceID
where (a.agencyid in (@agency))
and (a.startdate >= @startdate and a.enddate <= @enddate)
and TotalBilled is NOT NULL
ORDER BY TotalBilled ASC
) AS I
ORDER BY TotalBilled DESC)
答案 0 :(得分:1)
我相信您希望将行限制添加到子选择中,如下所示
DECLARE @Cnt int = (SELECT COUNT(TotalBilled) FROM InvoiceLine)
select
a.AgencyID
a.startdate,
a.enddate,
[TotalBilled],
((SELECT TOP 1 TotalBilled
FROM (
SELECT TOP (@Cnt/2) TotalBilled
FROM InvoiceLine I
WHERE TotalBilled is NOT NULL
and a.InvoiceID = I.InvoiceID --new
ORDER BY TotalBilled
) AS I
ORDER BY TotalBilled DESC) +
(
SELECT TOP 1 TotalBilled
FROM (
SELECT TOP (@Cnt/2) TotalBilled
FROM InvoiceLine I
WHERE TotalBilled is NOT NULL
and a.InvoiceID = I.InvoiceID --new
ORDER BY TotalBilled DESC
) AS I
ORDER BY TotalBilled ASC)) / 2 AS MedianTotalBilled
from Agency a
left join invoiceLine invl
on a.InvoiceID = invl.InvoiceID
where (a.agencyid in (@agency))
and (a.startdate >= @startdate and a.enddate <= @enddate)
编辑: 行数选择器也必须受到限制
select
a.AgencyID
a.startdate,
a.enddate,
[TotalBilled],
((SELECT TOP 1 TotalBilled
FROM (
SELECT TOP (
(
SELECT count(*)
FROM InvoiceLine I
WHERE TotalBilled is NOT NULL
and a.InvoiceID = I.InvoiceID
)
/2) TotalBilled
FROM InvoiceLine I
WHERE TotalBilled is NOT NULL
and a.InvoiceID = I.InvoiceID --new
ORDER BY TotalBilled
) AS I
ORDER BY TotalBilled DESC)
from Agency a
left join invoiceLine invl
on a.InvoiceID = invl.InvoiceID
where (a.agencyid in (@agency))
and (a.startdate >= @startdate and a.enddate <= @enddate)