大数据 爬虫Python AI Sql

mySQL 学习 DAY11笔记

2020-02-29  本文已影响0人  Peng_001

47 Subqueries in the SELECT Clause

SELECT 
    client_id,
    name,
    (SELECT SUM(invoice_total)
    FROM invoices
    WHERE c.client_id = client_id) AS total_sales,
    (SELECT AVG(invoice_total)
    FROM invoices) AS average,
    (SELECT total_sales - average) AS difference
FROM clients c    
## 输出client的name,总销售额,个人平均销售额以及二者的差值
SELECT 
    client_id,
    name,
    (SELECT AVG(invoice_total)
    ## 将SUM 改为 AVG
    FROM invoices
    WHERE c.client_id = client_id) AS total_sales,
    (SELECT AVG(invoice_total)
    FROM invoices) AS average,
    (SELECT total_sales - average) AS difference
FROM clients c    

即需要书写

 (SELECT total_sales - average) AS difference

而不能写成

total_sales - average AS difference
## 直接对SELECT的column 进行计算就可以直接引用

48 Subqueries in the FROM Clause

SELECT *
FROM (
    SELECT 
        client_id,
        name,
        (SELECT AVG(invoice_total)
        FROM invoices
        WHERE c.client_id = client_id) 
        AS total_sales,
        (SELECT AVG(invoice_total)
        FROM invoices) 
        AS average,
        (SELECT total_sales - average) AS difference
    FROM clients c 
    ) AS sales_summary
WHERE total_sales IS NOT NULL
##输出client的name,个人平均销售额,总平均销售额以及二者的差值,并排除无sales的client

49 Numeric Functions

  1. ROUND
SELECT ROUND(5.5343,2)
##保留两位小数(四舍五入),得到5.53
  1. TRUNCATE
SELECT TRUNCATE(5.5343,2)
##保留两位小数(直接删去后面的数字),得到5.53
  1. CEILING
SELECT CEILING(5.5343)
##得到比其大的最近整数,返回6
  1. FLOOR
SELECT FLOOR(5.5343)
##得到比其小的最近整数,返回5
  1. ABS
SELECT ABS(-5.5343)
##得到绝对值,返回5.5343
  1. RAND
SELECT RAND()
##返回一个random value between 0 to 1
上一篇 下一篇

猜你喜欢

热点阅读