我正在尝试购买品牌1品牌2或品牌3的商店数量,但是pne shop计数一次。但在我的查询中,它计算每个品牌的总行数。谁能纠正我的疑问?
--- product ---
id pcode pname brand
1 123 Dalda 1
2 124 Habib 1
3 125 Sufi 2
4 126 Toyota 3
---------SALE-----------
id shcode shname pcode pname amount
1 1 A G/S 123 DALDA 1020
2 1 A G/S 124 HABIB 1030
3 2 B G/S 125 SUFI 1040
4 2 B G/S 123 DALDA 1020
5 2 B G/S 126 TOYOTA 1050
6 3 C G/S 123 DALDA 1020
7 4 D G/S 125 SUFI 1040
8 4 D G/S 123 DALDA 1020
9 4 D G/S 124 HABIB 1030
10 4 D G/S 126 TOYOTA 1050
11 5 E G/S 123 DALDA 1020
12 6 F G/S 125 SUFI 1040
13 7 G G/S 126 TOYOTA 1050
MY REQUIRED RESULT
BRAND Shops
1 5
2 3
3 3
我的查询
select p.brand, count(s.shcode) AS shops
FROM product p
INNER JOIN sdetail s on s.pcode = p.pcode
GROUP BY p.brand
答案 0 :(得分:0)
SELECT tmp.brand, count(tmp.shcode) AS shops FROM (
SELECT DISTINCT temp.brand, (SELECT DISTINCT temp.shcode) AS shcode FROM (SELECT p.brand, s.shcode
FROM product p
INNER JOIN sdetail s on s.pcode = p.pcode) AS temp
) AS tmp GROUP BY tmp.brand
逻辑:加入两张桌子,获得不同的商店品牌对,按品牌分组并获得店铺数量。
答案 1 :(得分:0)
我认为你需要的是你的计数函数中的shcode。所以试试这个:
select p.brand, count(distinct(s.shcode)) AS shops
FROM product p
INNER JOIN sdetail s on s.pcode = p.pcode
GROUP BY p.brand
这是一个fiddle来玩这个..