我想知道每个部门注册最多的用户,关闭了 最。这些数据分布在3个表中 - Department和Closed在BATCH中 表,STORE表中的registered_by和ACCOUNT表中的用户名。
我正在尝试使用count和max聚合函数来获取此信息。
这是我写的查询:
SELECT
b.department_id,
s.regsitered_by,
b.closed_by,
a.username,
COUNT(s.regsitered_by) As "Total Regsitered",
COUNT(b.closed_by) As "Total Closed"
FROM [db].[store] as s
LEFT JOIN [db].[batch] b on b.id = s.batch_id
LEFT JOIN [db].[accounts] as a on a.id = b.closed_by
WHERE registered_by = (select max(regsitered_by)from [db].[store]) AND
closed_by = (select max(closed_by)from [db].[batch])
group by
b.department_id,
s.regsitered_by,
b.closed_by,
a.username
非常感谢任何建议。
我也试图使用临时表来保存结果,但这不是很有帮助
SELECT
b.department_id,
s.regsitered_by,
b.closed_by,
a.username,
COUNT(s.regsitered_by) AS "Total Regsitered",
COUNT(b.closed_by) AS "Total Closed"
INTO #TEMP1
FROM [db].[store] AS s
LEFT JOIN [db].[batch] AS b ON b.id = s.batch_id
LEFT JOIN [db].[accounts] AS a ON a.id = b.closed_by
GROUP BY
b.department_id,
s.regsitered_by,
b.closed_by,
a.username
SELECT *
FROM #temp1
WHERE registered_by = (SELECT MAX(regsitered_by)FROM [db].[store]) AND
closed_by = (SELECT MAX(closed_by)From [db].[batch])
DROP TABLE #temp1
答案 0 :(得分:0)
在where子句中,您正在检查以下条件..
WHERE registered_by = (select max(regsitered_by)from [db].[store]) AND
closed_by = (select max(closed_by)from [db].[batch])
这将在计数之前应用,因此您可能无法获得准确的结果。将该条款移至
SELECT
b.department_id,
s.regsitered_by,
b.closed_by,
a.username,
COUNT(s.regsitered_by) As "Total Regsitered",
COUNT(b.closed_by) As "Total Closed"
FROM [db].[store] as s
LEFT JOIN [db].[batch] b on b.id = s.batch_id
LEFT JOIN [db].[accounts] as a on a.id = b.closed_by
group by
b.department_id,
s.regsitered_by,
b.closed_by,
a.username
having
COUNT(s.regsitered_by)=(select max(regsitered_by)from [db].[store])
and
COUNT(s.closed_by)=(select max(closed_by)from [db].[batch])
答案 1 :(得分:0)
不允许排名(rank
,dense_rank
,row_number
)?那么,这里是如何让每个部门最关闭的人:
select counts.department_id, counts.closed_by
from
(
select department_id, closed_by, count(*) as cnt
from batch
group by department_id, closed_by
) counts
join
(
select department_id, max(cnt) as cnt
from
(
select department_id, count(*) as cnt
from batch
group by department_id, closed_by
) counts
) maxcounts on maxcounts.department_id = counts.department_id
and maxcounts.cnt = counts.cnt
对department_id, registered_by
执行相同操作,您必须加入两个表batch
和store
。
然后:
select
coalesce(c.department_id, r.department_id) as department_id,
(select username from account a where a.id = c.closed_by) as closer,
(select username from account a where a.id = c.registered_by) as registerer
from (<close_by query>) c
full outer join (<registered_by query>) r on r.department_id = c.department_id;
我应该补充一点,如果每个部门有多个最大关闭器或注册器,这不是最佳选择。对于X部门,我们有以下注册人:
user cnt emp1 20 emp2 30 emp3 30
以及以下关闭者;
user cnt emp1 15 emp2 10 emp4 15
然后我们得到:
dept max_registerer max_closer X emp2 emp1 X emp2 emp4 X emp3 emp1 X emp3 emp4
因此,您可能希望将此结果汇总到
dept max_registerer max_closer X emp2, emp3 emp1, emp4例如,
。 (如果是这样,请查看如何在SQL Server中模仿GROUP_CONCAT。)