这是原始数据
Book | Author | Year
A | A1 | 1985
A | B1 | 1985
B | A1 | 1988
B | C1 | 1988
D | A1 | 1990
D | C1 | 1990
D | B1 | 1990
以下是我要找的输出,
Author1 | Author2 | year | count
A1 | B1 | 1985 | 1
A1 | C1 | 1985 | 1
A1 | C1 | 1988 | 1
A1 | B1 | 1990 | 1
A1 | C1 | 1990 | 1
B1 | C1 | 1990 | 1
非常感谢任何帮助。 感谢
答案 0 :(得分:0)
SELECT A.author AS author1,
B.author AS author2,
A.year,
COUNT(*) AS "count"
FROM Author A
LEFT JOIN Author B
ON B.book = A.Book
AND B.author > A.Author
GROUP BY A.author, B.author, A.year
ORDER BY A.author, B.author, A.year
只要Author表中每本书的行数不超过两行,这样就可以正常工作。否则,它将为每本书产生多行。如果可能出现这种情况,则应指出应使用哪种SQL风格,因为限制表B结果的方法因实现而异。我已经任意选择按字母顺序列出作者,因为似乎没有指出哪个作者是“主要的”。
我希望表中还有其他列,你没有告诉我们 - 最具体的是一个主键,也许还有一些属性表明了作者关于给定书籍的“计费顺序”。
如果可能的话,您可能需要重新考虑您的表格设计:它采用非规范化形式,使数据完整性难以执行。
答案 1 :(得分:0)
您正在寻找的查询是具有聚合的自联接:
select t1.author as author1, t2.author as author2, t1.year, count(*) as `count`
from t t1 join
t t2
on t1.book = t2.book and
t1.author < t2.author
group by t1.author, t2.author, t1.year
order by t1.author, year;