zoukankan      html  css  js  c++  java
  • SQL 单表查询多个计算的值

    1.查询男女生各有多少人

    SELECT Sex,COUNT(ID) as Count FROM Students GROUP BY Sex

    2.

    统计男女生中未成年、成年的人数

    结果如下:

    性别 未成年 成年
    3 13
    2 18

    SQL语句:

    SELECT CASE WHEN Sex=0 THEN '男' ELSE '女' END AS '性别',
    SUM(CASE WHEN Age<18 THEN 1 ELSE 0 END) AS '未成年', 
    SUM(CASE WHEN Age>=18 THEN 1 ELSE 0 END) AS '成年'
    FROM Students
    GROUP BY Sex

    3.

    (1).第一种写法


    SELECT PoliceNumber ,
    SUM(CASE WHEN RentableArea !=0 and location ='南区' THEN RentableArea ELSE 0 END) AS HaveRent,
    SUM(CASE WHEN Area!=0 and location ='南区' THEN Area ELSE 0 END) AS TotalArea,
    (SUM(CASE WHEN Area!=0 and location ='南区' THEN Area ELSE 0 END)-SUM(CASE WHEN RentableArea !=0 THEN RentableArea ELSE 0 END)) as HaveNotRent
    FROM ShopInfo
    GROUP BY PoliceNumber

    (2).第二种写法

    select t1.PoliceNumber,t1.TotalArea,t2.HaveNotRent, ISNULL(t3.HaveRent,0) as HaveRent from
    (
    select PoliceNumber,sum(area) as TotalArea
    from FactoryInfo where location ='南区' group by PoliceNumber
    ) as t1 left join (
    select PoliceNumber, sum(isnull(cast(RentableArea as float),'0')) as HaveNotRent from FactoryInfo
    where location ='南区' group by PoliceNumber
    ) as t2 on t1.PoliceNumber=t2.PoliceNumber left join (
    select PoliceNumber, sum(isnull(
    cast(Area as float)-Cast(RentableArea as float),'0')) as HaveRent from FactoryInfo
    where location ='南区' group by PoliceNumber
    ) as t3 on t3.PoliceNumber=t2.PoliceNumber
    order by t1.PoliceNumber,cast(dbo.GetNoFromStr(t1.PoliceNumber) as int) asc

  • 相关阅读:
    Linux用户配置文件、口令配置文件、组配置文件
    Linux忘记Root密码怎么找回
    Linux运行级别及解释
    Maven获取resources的文件路径、读取resources的文件
    常见状态码100、200、300、400、500等
    JVM内存模型
    tcl使用小结
    MFQ&&PPDCS
    总结下自己在工作中有关联的TCP/IP协议
    二层交换机和三层交换机
  • 原文地址:https://www.cnblogs.com/2260827114com/p/7381270.html
Copyright © 2011-2022 走看看