[英]SQL Query to calculate percentage based on sums from several tables
I'm trying to calculate a Percentage of gaming sessions per console platform. 我正在尝试计算每个控制台平台的游戏会话百分比。 I 'm calculating usage based on data from two different sesssions-tables (one that just has a summary and one where I sum up per console).
我正在根据来自两个不同会话表的数据来计算使用情况(一个表只有一个摘要,而每个控制台中有一个摘要)。 That works, and I can sum the total nr or sessions into SessionTotal in T3.
那行得通,我可以将Nr或会话总数加到T3中的SessionTotal中。 So this code almost works, just can't seem to get the outer SELECT to validate.
因此,这段代码几乎可以正常工作,只是似乎无法让外部SELECT进行验证。 Could someone help me out?
有人可以帮我吗?
SELECT T3.Sessions, T3.Console, T3.Sessions * 100 / T2.SessionTotal AS Percentage
FROM
(
-- This call returns a total nr of sessions played
SELECT SUM(Sessions) as SessionTotal
FROM
(SELECT Sessions, Console, SystemID
FROM (SELECT TOP (100) PERCENT ISNULL(MIN(ps.SessionCount), 0) + ISNULL(COUNT(s.system_id), 0) AS Sessions, MIN(c.name) AS Console, MIN(c.id) AS SystemID
FROM dbo.[Systems] AS c LEFT OUTER JOIN
dbo.Sessions AS s ON c.id = s.system_id LEFT OUTER JOIN
dbo.PreviousSessions AS ps ON c.id = ps.SystemID
GROUP BY c.id) AS T1) as T2,
-- This call returns nr of sessions per system
SELECT Sessions, Console, SystemID
FROM (SELECT TOP (100) PERCENT ISNULL(MIN(ps.SessionCount), 0) + ISNULL(COUNT(s.system_id), 0) AS Sessions, MIN(c.name) AS Console, MIN(c.id) AS SystemID
FROM dbo.[Systems] AS c LEFT OUTER JOIN
dbo.Sessions AS s ON c.id = s.system_id LEFT OUTER JOIN
dbo.PreviousSessions AS ps ON c.id = ps.SystemID
GROUP BY c.id) AS T3
)
declare @SessionTotal float =
(
SELECT SUM(Sessions) as SessionTotal
FROM
(SELECT Sessions, Console, SystemID
FROM (
SELECT TOP (100) PERCENT ISNULL(MIN(ps.SessionCount), 0) + ISNULL(COUNT(s.system_id), 0) AS Sessions, MIN(c.name) AS Console, MIN(c.id) AS SystemID
FROM dbo.[Systems] AS c
LEFT OUTER JOIN dbo.Sessions AS s
ON c.id = s.system_id
LEFT OUTER JOIN dbo.PreviousSessions AS ps
ON c.id = ps.SystemID
GROUP BY c.id) AS T1
) as T2
)
SELECT Sessions, Console,Sessions * 100/@SessionTotal AS Percentage
FROM (
SELECT TOP (100) PERCENT ISNULL(MIN(ps.SessionCount), 0) + ISNULL(COUNT(s.system_id), 0) AS Sessions, MIN(c.name) AS Console, MIN(c.id) AS SystemID
FROM dbo.[Systems] AS c
LEFT OUTER JOIN dbo.Sessions AS s
ON c.id = s.system_id
LEFT OUTER JOIN dbo.PreviousSessions AS ps
ON c.id = ps.SystemID
GROUP BY c.id
) AS T3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.