zoukankan      html  css  js  c++  java
  • TSQL Beginners Challenge 3

    这是一个关于CTE的应用,这里我们用CTE实现阶乘 Factorial,首先来看一个简单的小实验,然后再来看题目。有的童鞋会问怎么没有2就来3了呢,惭愧,TSQL Beginners Challenge 2对应的题目我没能做出来。上代码:

    ;with cte as 
    (
    select num=1,fact=1 union all 
    select num=num+1,fact=fact*(num+1) from cte  where num<5
    )
    select * from cte

    上面的查询会有什么结果呢,大家可以粘到查询分析器里面看下,简单的实现了阶乘吧。CTE的递归是有层级限制的,写Blog的时候想不起来相关的语法结构,又懒得去查,偷个懒直接用num<5来限制下,以免报错。:)。有了这个打的,下面的题目就很容易了,现在我们来看题目吧:

    Introduction 

    This challenge though does not have any resemblance with the real time problem directly, but it measures about logical thinking. The problem is all about finding the factorial of numbers. Though it is known to most of us what a factorial is, but to recall the concept here is an example:

    Factorial of 3 is 1*2*3 = 6 i.e. the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n.

    Sample Data

    1.Nums
    2.-----------
    3.0
    4.1
    5.3
    6.5
    7.10 

    Expected Results 

    1.Nums        Factorial
    2.----------- -----------
    3.0                    1
    4.1                    1
    5.3                    6
    6.5                  120
    7.10             3628800
    --创建表
    CREATE TABLE [Fact](
        [Nums] [int] NULL
    ) 
    
    --构造数据
    insert into Fact(Nums) values(0)
    insert into Fact(Nums) values(1)
    insert into Fact(Nums) values(10)
    insert into Fact(Nums) values(3)
    insert into Fact(Nums) values(5)
    
    --方式一
    ;WITH cte AS 
    (
    SELECT num=0,factorial=1
    UNION ALL 
    SELECT num=num+1,(num+1)*factorial FROM cte WHERE num<10
    )
    SELECT Nums,factorial FROM cte a, Fact b WHERE a.num=b.Nums
     
  • 相关阅读:
    Prometheus环境搭建系列(三):监控redis服务器(redis_exporter)
    Java诊断神器:Arthas常用功能
    sql优化练习
    navicat:[Err] 1055
    Prometheus环境搭建系列(二):监控mysql服务器(mysqld_exporter)
    【笔试必备】常见sql笔试题
    将博客搬至CSDN
    springboot假死、连接泄露
    测试字符串
    阿里云初次使用教程
  • 原文地址:https://www.cnblogs.com/mfkaudx/p/3571923.html
Copyright © 2011-2022 走看看