使用子查询进行SQL查询

时间:2016-12-18 07:46:39

标签: mysql sql subquery

我目前正在做一个SQL问题。

问:对于每个制造商,将PC,笔记本电脑和打印机的数量作为它们生成的countOFPC,countOfLaptop,countOfPrinter。

数据库方案由四个表组成:产品(制造商,型号,类型)

“产品”表包含有关制造商,型号和类型(“PC”,“笔记本电脑”或“打印机”)的信息。假设Product表中的型号对于所有制造商和产品类型都是唯一的。

这是我尝试过的,但它无法正常工作。

  select distinct  maker, 
            (select count(* )               
            from Product p
           where p.maker=maker and p.type='Laptop')countOfLaptop,

                         (select count(*)     
                         from Product p
                         where p.maker=maker and p.type='PC') countOfPc,
                                                        (select count(*)     
                                                         from Product p
                                                         where p.maker=maker and p.type='Printer') countOFPrinter

来自产品

有什么问题,我该如何纠正?

2 个答案:

答案 0 :(得分:0)

你应该改为:

SELECT 
    SUM(CASE WHEN type = 'PC' THEN 1 ELSE 0 END) countOfPc, 
    SUM(CASE WHEN type = 'Laptop' THEN 1 ELSE 0 END) countOfLaptop, 
    SUM(CASE WHEN type = 'Printer' THEN 1 ELSE 0 END) countOfPrinter 
FROM 
    product;

如果您只计算唯一model number,则可以使用此代码:

SELECT 
    SUM(CASE WHEN type = 'PC' THEN 1 ELSE 0 END) countOfPc, 
    SUM(CASE WHEN type = 'Laptop' THEN 1 ELSE 0 END) countOfLaptop, 
    SUM(CASE WHEN type = 'Printer' THEN 1 ELSE 0 END) countOfPrinter 
FROM (
    SELECT DISTINCT 
        model, type 
    FROM 
        product
);

答案 1 :(得分:0)

扩展@Pharm X.Bach所说的话。您已经说过,每个“制造商”都需要这些信息

您也可以使用CTE(公用表格表达式)

WITH ProductFlags AS (
  SELECT MODEL,
         TYPE,
         MAKER,
         (CASE WHEN TYPE = 'PC' THEN 1 ELSE 0 END) AS flgPrdTypePC,
         (CASE WHEN TYPE = 'Laptop' THEN 1 ELSE 0 END) AS flgPrdTypeLaptop,
         (CASE WHEN TYPE = 'Printer' THEN 1 ELSE 0 END) AS flgPrdTypePrinter
   FROM PRODUCT
)
  SELECT SUM(flgPrdTypePC) AS countOfTypePC,
         SUM(flgPrdTypeLaptop) AS countOfTypeLaptop,
         SUM(flgPrdTypePrinter) AS countOfTypePrinter,
         MAKER
    FROM ProductFlags
GROUP BY MAKER;

或者没有基于带有子查询的标志的CTE

SELECT SUM(flgPrdTypePC) AS countOfTypePC,
       SUM(flgPrdTypeLaptop) AS countOfTypeLaptop,
       SUM(flgPrdTypePrinter) AS countOfTypePrinter,
       MAKER
  FROM (SELECT MODEL,
               TYPE,
               MAKER,
               (CASE WHEN TYPE = 'PC' THEN 1 ELSE 0 END) AS flgPrdTypePC,
               (CASE WHEN TYPE = 'Laptop' THEN 1 ELSE 0 END) AS flgPrdTypeLaptop,
               (CASE WHEN TYPE = 'Printer' THEN 1 ELSE 0 END) AS flgPrdTypePrinter
          FROM PRODUCT)
GROUP BY MAKER;

P.S。我建议在将 TYPE 列与值ex进行比较时考虑使用 UPPER UPPER(TYPE) = 'PC' or UPPER(TYPE) = UPPER('PC') 如果您100%确定您的数据,那么请继续使用上述解决方案。