我正在努力为以下场景编写一个sql查询,希望能提供任何指针:
我的数据是这样存储的:
区域名称| SessionId
1区| 1
2区1
3区1
1区| 1
1区| 2区
2区| 2
2 | 3区
3区| 3
2 | 3区
(请注意,一次会话中用户可以多次进入同一区域)
我想生成一个输出,显示进入一个区域的人同时进入另一个区域的百分比(即进入1区的人中66%也进入2区):
1区| 2区| 3区
1区100%| 66%| 33%
2区66%| 100%| 66%
3区33%| 66%| 100%
有没有一个特定的内置SQL函数来做这样的事情?有人能就如何实现这一目标提出建议吗?
谢谢
汤姆
使用PostgreSQL的p.s
在这里小提琴:http://sqlfiddle.com/#!15/f379c/1/0
最佳答案
因此,如果您可以在应用程序端处理一些转换:
DECLARE @ZoneCounts TABLE
(
Zone nvarchar(max),
sessionId int
)
INSERT INTO @ZoneCounts
values
('Zone 1', 1),
('Zone 2', 1),
('Zone 3', 1),
('Zone 1', 2),
('Zone 2', 2)
select v3.down, v3.across, convert(decimal(13,2),(CONVERT(decimal(13,2), v3.matchingSessions) / v3.sessionsVisitingDown) * 100) as percentage
from
(SELECT v2.down, v2.across, v2. matchingSessions, max(v2.matchingSessions) over (partition by v2.down) as sessionsVisitingDown
FROM (select down, across, matchingSessions from
(select lhs.Zone as down, rhs.Zone as across, count(lhs.sessionId) over (partition by lhs.Zone, rhs.Zone) as matchingSessions
from @ZoneCounts as lhs inner join @ZoneCounts as rhs on lhs.sessionId = rhs.sessionId) AS v1
GROUP BY down, across, matchingSessions) AS v2)
as v3
给你
NB-使用MS SQL,但应转换
啊,Postgres不太一样
SELECT v3.down, v3.across, cast(cast(v3.matchingSessions as decimal) / cast(v3.sessionsVisitingDown as decimal) * 100 as decimal(13,2)) AS percentage
FROM
(SELECT v2.down, v2.across, v2. matchingSessions, max(v2.matchingSessions) over (partition BY v2.down) AS sessionsVisitingDown
FROM (SELECT down, across, matchingSessions FROM
(SELECT lhs.name AS down, rhs.name AS across, count(lhs.id) over (partition BY lhs.name, rhs.name) AS matchingSessions
FROM ItemList AS lhs INNER JOIN ItemList AS rhs ON lhs.id = rhs.id) AS v1
GROUP BY down, across, matchingSessions) AS v2)
AS v3
这里有一个SQL小提琴:http://sqlfiddle.com/#!15/f379c/13/0使用PostgreSQL
关于sql - 如何使用SQL从表中创建矩阵类型结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23627159/