sql的一些高级查询

xiaoxiao2021-03-01  40

group by结合having

统计部门不为总经办的总工资大于100的部门

select sum(salary),emp from emp_salary e where e.emp not in ("总经办") group by e.emp having > 100

多表子查询

eg:

SELECT P.ProductID, P.Name, P.ProductNumber, M.Name AS ProductModelName FROM Production.Product AS P INNER JOIN (SELECT Name, ProductModelID FROM Production.ProductModel) AS M ON P.ProductModelID = M.ProductModelID

结合cout使用,统计某一个产品销量多少,需要显示产品的名称

SELECT P.ProductID, P.Name, P.ProductNumber, M.fee AS fee FROM Production.Product AS P INNER JOIN (SELECT ProductModelID,count(*) FROM Production.ProductModel group by ProductModelID) AS M ON P.ProductModelID = M.ProductModelID

case when then用法

普通用法

查询user表里面的成员性别,当sex为1的时候为“男”,为“0”的时候为女,否则为其他

select u.id,u.name,u.sex, (case u.sex when 1 then '男' when 2 then '女' else '其他' end )性别 from users u; 查询结果显示: ID NAME SEX 性别
1 张一 空的 2 张二 1 男 3 张三 空的 4 张四 空的

如果不希望显示sex的话,sql语句为:

select u.id,u.name, ( case u.sex when 1 then "男", when 2 then "女" else "其他" end )性别 from user u
与sum和count结合进行统计

与sum结合,查询男生和女生分别有多少人

select sum(case u.sex when 1 then 1 else 0 end)男性, sum(case u.sex when 2 then 1 else 0 end)女性, sum(case when u.sex <> 2 and s.sex <> 1 then 1 else 0 end)其他 from user u

与count结合

select count(case u.sex when 1 then 1 end)男性, count(case when u.sex=2 then 1 end)女, count(case when u.sex <>1 and u.sex<>2 then 1 end)性别为空 from users u;

上面两个结果都:

男性 性别为空 ---------- ---------- ---------- 3 2 0

统计某一段年龄区间的人数,按性别区分

select u.sex, (sum(case when u.age <= 20 then 1 else 0 end) as '[0-20]的人', sum(case when u.age between 21 and 40 then 1 else 0 end) as '(20-40]的人'sum(case when u.age >40 then 1 else 0 end) as 40岁以上的人 ) from user u group by u.sex

特殊情况,查询出来的字段转换成int

在SQL SERVER 2005中,将表中字符串转换为数字的函数共2个: 1. convert(int,字段名) 例如:select convert(int,’fee’) 2. cast(字段名 as int) 例如:select cast(‘fee’ as int) 其实,一般情况下没有必要把字符串转换为数字类型

计算多个字段的和

select a+b as C from tables
转载请注明原文地址: https://www.6miu.com/read-4550121.html

最新回复(0)