2

我正在尝试计算购买品牌 1 品牌 2 或品牌 3 的商店数量。但 pne 商店计数一次。但在我的查询中,它计算每个品牌的总行数。谁能更正我的查询?

                            --- 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
4

2 回答 2

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

逻辑:加入两张表,得到不同的店铺品牌对,按品牌分组,得到店铺数量。

于 2013-02-05T05:59:30.943 回答
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

这是一个玩这个的小提琴..

于 2013-02-05T06:27:18.820 回答