表1:关键字
ItemID KWtype KWvalue
1 Brand Nike
2 Brand Nike
1 Type Soccer
4 Brand adidas
表2:项目
ItemID SiteID CategoryID ItemName
1 0 10 Shoe1
2 0 10 Shoe2
3 2 55 Shoe3
4 1 11 Shoe4
我有这两张桌子(他们当然要大得多)
如何继续了解Site = 0和Category = 10中最常出现的10个品牌? 我想在一列中列出前10名(排名前10位的品牌),在另一栏中,我想计算它们出现的次数
由于
答案 0 :(得分:0)
首先,您应该真正调整数据模型。它可以更有效地工作,更容易理解
表:品牌
ID ItemID BrandName
1 1 Nike
2 2 Nike
3 4 adidas
表:类型
ID ItemID TypeName
1 1 Soccer
表:项目
ID SiteID CategoryID ItemName
1 0 10 Shoe1
2 0 10 Shoe2
3 2 55 Shoe3
4 1 11 Shoe4
构建外键,将品牌和类型表中的ItemID链接到items表中的ID。
然后你可以运行像这样的查询
SELECT brandname as Brand, count(brand.id) as Qty
FROM brands
LEFT JOIN items ON items.id = brand.itemid
WHERE siteID = 0 AND categoryID = 10
GROUP BY brandname
ORDER BY qty DESC
LIMIT 10
答案 1 :(得分:0)
这将计算:
SELECT k.KWvalue as Brand, count(*) as Qty
FROM items as i
JOIN keywords as k
ON i.itemid = k.itemid
WHERE k. KWtype = Brand
AND i.siteID = 0
AND i.categoryID = 10
GROUP BY k.KWvalue
返回前10个计数取决于您的DBMS。
Darren H已经为mysql编写了它,只需添加
ORDER BY qty DESC
LIMIT 10
Teradata:
SELECT k.KWvalue as Brand, count(*) as Qty
FROM items as i
JOIN keywords as k
ON i.itemid = k.itemid
WHERE k. KWtype = Brand
AND i.siteID = 0
AND i.categoryID = 10
GROUP BY k.KWvalue
QUALIFY RANK() OVER (ORDER BY Qty DESC) <= 10
Oracle(以及大多数其他DBMS):
SELECT Brand, Qty
FROM
(
SELECT k.KWvalue AS Brand, COUNT(*) AS Qty, RANK() OVER (ORDER BY Qty DESC) AS rnk
FROM items AS i
JOIN keywords AS k
ON i.itemid = k.itemid
WHERE k. KWtype = Brand
AND i.siteID = 0
AND i.categoryID = 10
GROUP BY k.KWvalue
) dt
WHERE rnk <= 10