我有以下查询:
select AP.paper_id as id,
concat(A.organization, A.country)as org,
group_concat(SUBSTR(first_name, 1, 1), '. ', last_name SEPARATOR ', ') as initial
from authors A
inner join authors__papers AP ON A.author_id = AP.author_id
join tmp_orgs ORGS ON ORGS.paper_id = AP.paper_id
where ORGS.organization=A.organization AND
AP.is_contact_author < 1
group by A.organization, AP.paper_id
order by AP.paper_id, idx
它将数据输出到:
id org initial
1001 org1 J. Doe
1001 org1 J.Smith
1003 org2 A. Doe
1004 org3 A. Smith
1004 org3 B. Doe
1006 org4 B. Smith
1007 org5 C. Doe
我需要的是第4列,它是按paper_id分组的所有组织的计数,因此结果如下:
id org initial org_count
1001 org1 J. Doe 2
1001 org1 J.Smith 2
1003 org2 A. Doe 1
1004 org3 A. Smith 2
1004 org3 B. Doe 2
1006 org4 B. Smith 1
1007 org5 C. Doe 1
我厌倦了添加子查询:
(SELECT COUNT(DISTINCT(组织))作为来自作者的dcnt A INNER JOIN authors__papers AP on AP.author_id = A.author_id其中AP.is_contact_author&lt; 1 AND paper_id = ??? GROUP BY paper_id)as org_count
...但是无法弄清楚如何为每一行指定paper_id(上面的查询中的???。并且最好将它作为select中的连接或列,或者它真的重要吗?我不是一个真正的SQL人,但需要它,因为我正在为某人填写。感谢任何帮助!
答案 0 :(得分:1)
你快到了,试试这个:
SELECT
AP.paper_id AS id,
CONCAT(A.organization, A.country) AS org,
GROUP_CONCAT(SUBSTR(first_name, 1, 1), '. ', last_name SEPARATOR ', ') AS initial,
(
SELECT COUNT(DISTINCT(organization)) AS dcnt
FROM authors t1
INNER JOIN authors__papers t2 ON t2.author_id = t1.author_id
-- INNER JOIN tmp_orgs t3 ON t3.paper_id = t2.paper_id AND t3.organization = t1.organization
WHERE t2.is_contact_author < 1
) AS org_count
FROM authors A
INNER JOIN authors__papers AP ON A.author_id = AP.author_id
INNER JOIN tmp_orgs ORGS ON ORGS.paper_id = AP.paper_id
WHERE ORGS.organization = A.organization
AND AP.is_contact_author < 1
GROUP BY A.organization, AP.paper_id
ORDER BY AP.paper_id, idx