我有一个 SQL 报告,用于计算字段实例的数量。我正在将其纳入总结报告中。这可以使用 Lookupset 函数来实现。但是,我想计算该列的总计并找到行的百分比。 例如:
首选雇主 = 是,首选雇主 = 否 我希望能够在计数列旁边添加一个百分比列,以显示每行的百分比。 最终结果总计为 100
计数公式: =Join(LookupSet(Fields!pscode.Value, Fields!pscode.Value, Fields!PrefCnt.Value, "PrefEmployer"), vbCrLF + vbCrLF)
总计: =RunningValue(Fields!PrefCnt.Value,Sum,"PrefEmployer")
百分比:
=IIF(RunningValue(Fields!PrefCnt.Value,Sum,"PrefEmployer") <> 0, Join(LookupSet(Fields!pscode.Value, Fields!pscode.Value, Fields!PrefCnt.Value, "PrefEmployer"), vbCrLF + vbCrLF)/RunningValue(Fields!PrefCnt.Value,Sum,"PrefEmployer")*100,0)
SELECT
vt.pscode as pscode,
vt.PrefEmpl as PrefEmpl,
SUM(vt.PrefCnt) as PrefCnt
FROM
(
SELECT
rtrim(p.sAddr1) + ' (' + rtrim(p.sCode) + ')' pscode,
isnull(ltrim(lb.sPrefEmployer), 'No') PrefEmpl,
count(lb.sPrefEmployer) PrefCnt
FROM
property p (nolock)
INNER JOIN tenant t (nolock) on p.hMy = t.hProperty
INNER JOIN Leasebut28 lb (nolock) on t.hMyPerson = lb.hCode
INNER JOIN tenstatus ts (nolock) ON (t.istatus = ts.istatus)
WHERE
(
t.dtMoveIn <= '2022-08-22'
and (
t.dtMoveOut > '2022-08-22'
or t.dtMoveOut is null
)
)
AND ts.Status in ('Current', 'Future', 'Notice')
AND t.sUnitCode NOT IN ('COMAREA', 'WAIT')
AND t.sUnitCode NOT LIKE ('NONRES%')
AND lb.sCorp <> 'Yes'
and p.scode = 'carcen2'
GROUP BY
rtrim(p.sAddr1) + ' (' + rtrim(p.sCode) + ')',
lb.sPrefEmployer
UNION ALL
SELECT
rtrim(p.sAddr1) + ' (' + rtrim(p.sCode) + ')' pscode,
isnull(ltrim(b.sPrefEmployer), 'No') PrefEmpl,
count(b.sPrefEmployer) PrefCnt
FROM
room r (nolock)
INNER JOIN tenant t (nolock) ON (t.hmyperson = r.hmytenant)
INNER JOIN unit u (nolock) ON (u.hmy = t.hunit)
INNER JOIN unittype ut (nolock) on (ut.hMy = u.hUnitType)
INNER JOIN tenstatus ts (nolock) ON (t.istatus = ts.istatus)
INNER JOIN property p (nolock) ON (p.hmy = t.hproperty)
LEFT OUTER JOIN RoomBut1 b (nolock) ON (r.hMyPerson = b.hCode)
WHERE
isnull(r.dtmoveout, '01/01/2400') > Getdate()
AND (
t.dtMoveIn <= '2022-08-22'
and (
t.dtMoveOut > '2022-08-22'
or t.dtMoveOut is null
)
)
AND r.sRelationship <> 'Guarantor'
AND ts.Status in ('Current', 'Future', 'Notice')
AND t.sUnitCode NOT IN ('COMAREA', 'WAIT')
AND t.sUnitCode NOT LIKE ('NONRES%')
AND r.bOccupant <> -1
and p.scode = 'carcen2'
GROUP BY
rtrim(p.sAddr1) + ' (' + rtrim(p.sCode) + ')',
b.sPrefEmployer
) vt
GROUP BY
vt.pscode,
vt.PrefEmpl
Order by 2
我可能误解了这一点,但如果您只想获得每个 pscode 的“是”与“否”百分比份额,那么您可以将查询更改为
SELECT
vt.pscode as pscode,
vt.PrefEmpl as PrefEmpl,
SUM(vt.PrefCnt) as PrefCnt
FROM
(
...
... existing subquery here
...
) vt
GROUP BY
vt.pscode,
vt.PrefEmpl
Order by 2
到
SELECT DISTINCT
vt.pscode as pscode,
vt.PrefEmpl as PrefEmpl,
SUM(vt.PrefCnt) OVER(PARTITION BY vt.pscode, vt.PrefEmpl) as PrefCnt
SUM(vt.PrefCnt) OVER(PARTITION BY vt.pscode, vt.PrefEmpl)
/ SUM(vt.PrefCnt) OVER(PARTITION BY vt.pscode)
as PrefCntPercent
FROM
(
...
... existing subquery here
...
) vt
Order by 2