我正在尝试编写一个查询,我想返回对某个表贡献最多的用户。为了简化案例,让我们想象许多用户可以编写许多段落,这些段落最终会显示为一个完整的故事。下面是表结构(我给出了这个结构,而不是我的设计,但我至少构建了列名;)
paragraphs
-----
id (PK)
story_id (imaginary FK that I need to group the results by)
user_id (FK to userprop.id)
body
date
userprop
----
id (PK)
supervisor_id (FK to supervisors.id)
username (FK to users.name)
users
----
name
full_name
supervisors
----
id
full_name
我正在尝试编写一个查询,其中我得到每个段落,但有两个额外的列显示大多数时间使用的主管名称和主管监督的实际数量。
我一直在摆弄内部联接子查询,尝试在主选择中查询我的方式到结果并尝试按子查询进行分组。有些方法甚至不是有效的SQL而其他方法尚未解决,因为我不确定如何按supervisors.id
分组userprop.supervisor_id
分组paragraphs.user_id
{{1} }}
这可以在一个查询中完成,还是我必须合并一些PHP并使用多个查询和一些循环?
我只读了对数据库的访问权。
示例数据:
userprop.id
答案 0 :(得分:2)
您只需要一个简单的partitioned COUNT
。
示例数据
DECLARE @paragraphs TABLE (id int, story_id int, user_id int, body nvarchar(max));
INSERT INTO @paragraphs(id, story_id, user_id, body) VALUES
(1, 1, 1, 'Sample data'),
(2, 1, 1, 'Sample data'),
(3, 2, 1, 'Sample data'),
(4, 1, 2, 'Sample data'),
(5, 1, 3, 'Sample data'),
(6, 5, 1, 'Sample data');
DECLARE @userprop TABLE (id int, supervisor_id int, username nvarchar(50));
INSERT INTO @userprop (id, supervisor_id, username) VALUES
(1, 1, 'user_abc'),
(2, 1, 'user_def'),
(3, 2, 'user_ghi');
DECLARE @supervisors TABLE (id int, full_name nvarchar(50));
INSERT INTO @supervisors (id, full_name) VALUES
(1, 'Steve Doppler'),
(2, 'Frank Frampton');
<强>查询强>
SELECT
paragraphs.id
,paragraphs.story_id
,paragraphs.user_id
,paragraphs.body
,COUNT(*) OVER (PARTITION BY paragraphs.story_id, supervisors.id) AS main_supervisor_count
,supervisors.full_name AS main_supervisor
FROM
@paragraphs AS paragraphs
INNER JOIN @userprop AS userprop ON userprop.id = paragraphs.user_id
INNER JOIN @supervisors AS supervisors ON supervisors.id = userprop.supervisor_id
ORDER BY
paragraphs.id;
<强>结果强>
+----+----------+---------+-------------+-----------------------+-----------------+
| id | story_id | user_id | body | main_supervisor_count | main_supervisor |
+----+----------+---------+-------------+-----------------------+-----------------+
| 1 | 1 | 1 | Sample data | 3 | Steve Doppler |
| 2 | 1 | 1 | Sample data | 3 | Steve Doppler |
| 3 | 2 | 1 | Sample data | 1 | Steve Doppler |
| 4 | 1 | 2 | Sample data | 3 | Steve Doppler |
| 5 | 1 | 3 | Sample data | 1 | Frank Frampton |
| 6 | 5 | 1 | Sample data | 1 | Steve Doppler |
+----+----------+---------+-------------+-----------------------+-----------------+