我有一张类似波纹管的桌子。我想获取每天的访问用户数和角色。
表格:
CREATE TABLE #TempUser
(
[Id] int NULL,
[Username] nvarchar(50) NULL
)
CREATE TABLE #TempRole
(
[Id] int NULL,
[Title] nvarchar(50) NULL
)
CREATE TABLE #TempUserRole
(
[UserId] int NULL,
[RoleId] int NULL,
[LastDate] date NULL
)
数据:
INSERT INTO #TempUser([Id],[UserName])
VALUES
(1,'Marvin'),
(2,'Tom'),
(3,'Charli')
INSERT INTO #TempRole([Id],[Title])
VALUES
(1,'Admin'),
(2,'Manager'),
(3,'Guest')
INSERT INTO #TempUserRole([UserId],[RoleId],[LastDate])
VALUES
(1,1,'2019-02-03'),
(1,2,'2019-02-06'),
(1,2,'2019-02-03'),
(3,3,'2019-02-03'),
(3,1,'2019-02-02'),
(3,1,'2019-02-03'),
(2,1,'2019-02-05'),
(2,1,'2019-02-05'),
(3,1,'2019-02-03'),
(1,1,'2019-02-03'),
(2,1,'2019-02-06'),
(2,1,'2019-02-03'),
(1,1,'2019-02-03'),
(2,1,'2019-02-02'),
(1,1,'2019-02-03'),
(2,1,'2019-02-05'),
(1,1,'2019-02-05'),
(2,1,'2019-02-03')
如何获取每天具有相同“用户”,“角色”,“日期”,“ CounterOfDay”的用户列表的访问用户数和角色?我需要的输出应如下所示:
UserName Role Date CounterOfDay
Charli Admin 2019-02-02 2
Tom Admin 2019-02-02 2
...
答案 0 :(得分:1)
这是您的答案,但是请检查它是否可能存在任何语法错误,因为我不太经常为SQL-Server写查询。
WITH counters AS (
SELECT UserId, RoleId, LastDate, COUNT(*) AS CounterOfDay
FROM TempUserRole
GROUP BY UserId, RoleId, LastDate
)
SELECT
user.UserName
, role.Title
, counters.LastDate
, counters.CounterOfDay
FROM counters
JOIN TempRole AS role ON counters.RoleId = TempRole.Id
JOIN TempUser AS user ON counters.UserId = TempUser.Id
我认为阅读起来非常不错,并且应该比第一次进行连接时表现更好。
答案 1 :(得分:1)
您可以尝试以下操作。这是demo
with cte as
(
select
userName,
title,
lastDate,
count(*) as total
from tempUserRole tur
join tempUser tu
on tur.userId = tu.id
join tempRole tr
on tur.roleId = tr.id
group by
userName,
title,
lastDate
),
rnk as
(
select
*,
dense_rank() over (order by lastDate, title, total) as rnk
from cte
),
cnt as
(
select
*,
count(*) over (partition by rnk) as ttl
from rnk
)
select
userName,
title,
lastDate,
total
from cnt
where ttl > 1