我是SQL的新手,我尽最大努力编写代码,但它似乎对我不起作用,所以非常感谢帮助。
问题是我需要列出每个发布者发布的图书总数,然后使用发布商代码从最高和最低列出它们。
我已经走到了这一步;
SELECT COUNT (pub_code)
FROM Library_Books
GROUP BY pub_code
ORDER BY pub_code
无论如何都会感激任何帮助
答案 0 :(得分:1)
SELECT kb_pub_code, COUNT (kb_pub_code)
FROM Library_Books
GROUP BY kb_pub_code
ORDER BY 2
答案 1 :(得分:1)
你非常接近:
SELECT kb_pub_code, COUNT(*) TotalBooks
FROM Library_Books
GROUP BY kb_pub_code
ORDER BY TotalBooks DESC
TotalBooks
是count列的别名,它计算每个kb_pub_code
的总行数
您可以在ORDER BY
中引用列别名:ie。ORDER BY TotalBooks DESC
注意,如果可以在Library_Books
表中重复书籍,您可能需要DISTINCT
计数。类似的东西:
SELECT kb_pub_code, COUNT(DISTINCT title) TotalBooks
FROM Library_Books
GROUP BY kb_pub_code
ORDER BY TotalBooks DESC
答案 2 :(得分:0)
SELECT kb_pub_code
,COUNT (*) as 'TotalBooks'
FROM Library_Books
GROUP BY kb_pub_code
ORDER BY TotalBooks desc
编辑:有了可能重复的附加信息,您可能希望使用CTE。
With DistinctList as(
Select Distinct kb_pub_code as 'PubCode'
,kb_title as 'Title'
FROM Library_Books)
Select PubCode
,Count(*) as 'TotalBooks'
From DistinctList
Group by PubCode
ORDER BY TotalBooks desc
答案 3 :(得分:0)
ORDER BY
DESC
将按降序排序。发布商代码应包含在结果集(SELECT
)中,否则您将不知道哪个发布者是计数。
SELECT kb_pub_code, COUNT (kb_pub_code)
FROM Library_Books
GROUP BY kb_pub_code
ORDER BY COUNT(kb_pub_code) DESC