如何使用名称 Select SQL 中出现次数最多的项目

How to Select the Most Occuring Items in SQL with Names

我正在尝试 select 出现次数最多的项目。此代码有效,但我不知道如何从 Item table 中获取它各自的 ItemName 而不会出错

SELECT 
     TransactionDetail.ItemID, COUNT(*) AS 'AmountSold'
FROM TransactionDetail
GROUP BY TransactionDetail.ItemID
ORDER BY COUNT(*) DESC 

尝试的代码:

SELECT 
      TransactionDetail.ItemID, 
      COUNT(*) AS 'AmountSold'
FROM TransactionDetail
JOIN Item
ON Item.ItemID = TransactionDetail.ItemID
WHERE Item.ItemID = TransactionDetail.ItemID
GROUP BY TransactionDetail.ItemID
ORDER BY COUNT (*) DESC
SELECT TransactionDetail.ItemID9
      ,Item.ItemName
      , COUNT(*) AS [AmountSold]
FROM TransactionDetail
INNER JOIN Item  ON Item.ItemID = TransactionDetail.ItemID
GROUP BY TransactionDetail.ItemID , Item.ItemName
ORDER BY AmountSold DESC

我不确定项目 table 中有多少项目,但您可以通过在初始 select 语句之后向上滚动查询来对计数进行分组。

例如

Select
Case When rollup.ItemName like 'itemName1' Then count(rollup.ItemID) end as 'itemName1',
Case When rollup.ItemName like 'itemName2' Then count(rollup.ItemID) end as 'itemName2',
Case When rollup.ItemName like 'itemName3' Then count(rollup.ItemID) end as 'itemName3',

from 
(
Select Item.ItemName,
TransactionDetail.ItemID

FROM TransactionDetail
JOIN Item
ON Item.ItemID = TransactionDetail.ItemID
WHERE Item.ItemID = TransactionDetail.ItemID

)as rollup 

--你可以在此处的末尾加上一个 order by 来按降序列出结果。如果您有数千个项目,这将不是最好的方法。