如何在此SQL练习中使用row_number和case语句?

时间:2016-03-07 00:32:04

标签: sql

我正在做一个sql练习而且卡住了。如果我有计算机公司http://sql-ex.ru/help/select13.php#db_1中的数据库模式,问题描述为:

  

从Product表重新编号唯一对{maker,type},按如下方式对它们进行排序:
    - 升序制造商(制造商)的名称;
    - 订单中的产品类型(类型):PC,笔记本电脑,打印机   如果制造商生产多种类型的产品,则仅在第一行中推断其名称;
  此制造商的其他行应包含空字符串('')。

我的查询:

select 
    row_number() over (ORDER BY 
        maker ASC, 
        CASE type when 'PC' THEN 1 WHEN 'Laptop' THEN 2 WHEN 'Printer' THEN 3 END
    ) num, 
    maker, type 
from product 
order by maker, CASE type when 'PC' THEN 1 WHEN 'Laptop' THEN 2 WHEN 'Printer' THEN 3 END

我的(不正确)答案:

+-----+-------+---------+
| num | maker |  type   |
+-----+-------+---------+
|   1 | A     | PC      |
|  10 | C     | Laptop  |
|  11 | D     | Printer |
|  12 | D     | Printer |
|  13 | E     | PC      |
|  14 | E     | PC      |
|  15 | E     | PC      |
|  16 | E     | Printer |
|   2 | A     | PC      |
|   3 | A     | Laptop  |
|   4 | A     | Laptop  |
|   5 | A     | Printer |
|   6 | A     | Printer |
|   7 | A     | Printer |
|   8 | B     | PC      |
|   9 | B     | Laptop  |
+-----+-------+---------+

正确答案如下:

+-----+-------+---------+
| num | maker |  type   |
+-----+-------+---------+
|   1 | A     | PC      |
|   2 |       | Laptop  |
|   3 |       | Printer |
|   4 | B     | PC      |
|   5 |       | Laptop  |
|   6 | C     | Laptop  |
|   7 | D     | Printer |
|   8 | E     | PC      |
|   9 |       | Printer |
+-----+-------+---------+

修改

这就是网站在SQL支持方面所说的:Now we use Microsoft SQL Server 2012 on the rating stages, and MySQL 5.5.11, PostgreSQL 9.0, and Oracle Database 11g on the learn stage in addition.。这个问题来自学习阶段。

2 个答案:

答案 0 :(得分:1)

下面的查询将给出MySql的预期输出:

select rank, manufacturer, type 
from (
  select @r:=@r+1 AS rank,
  if( @lastmaker = maker, '', maker ) as manufacturer, 
  type, @lastmaker := maker
  from product, (SELECT @r:=0, @lastmaker:='') r
  order by maker, type
) mytable;

以下是SQL Fiddle

答案 1 :(得分:0)

我能够为此构建一个查询:

Select 
row_number() OVER(
ORDER BY maker,
CASE    WHEN type = 'PC' THEN '1'
        WHEN type = 'Laptop' THEN '2'
        WHEN type = 'Printer' THEN '3'
        ELSE type  END ASC) num,
CASE WHEN 
row_number() OVER(
PARTITION BY maker
ORDER BY CASE   WHEN type = 'PC' THEN '1'
                WHEN type = 'Laptop' THEN '2'
                WHEN type = 'Printer' THEN '3'
                ELSE type  END ASC) =1
                THEN maker
                ELSE '' END as maker,
type 
FROM
(select distinct maker,type from product) as p