Sql Server 子查询和复习分组数据





select * from Customers; --顾客信息表

select * from OrderItems; --实际物品表

select * from Orders; -- 顾客订单表 管理顾客表(cust_id)

select * from Products; --产品表 关联供应商表(vend_id)

select * from Vendors; --供应商表

--子查询就是把硬编码条件变成了软条件进行灵活查询
select * from Customers where cust_id in(
select cust_id from orders where cust_id in
(select cust_id from OrderItems where OrderItems.prod_id='RGAN01'));





select Vendors.vend_id,Vendors.vend_name,Products.prod_name,Products.prod_price from Vendors,Products where Products.prod_price in
(
select prod_price from Products
);










select prod_id, count(prod_price) from Products group by prod_id




select * from Products where COUNT(prod_price)>=0;

select * from Products where avg(prod_price)>=0;

-- GROUP BY (对查询数据进行分组)

/*GROUP BY 子句用于 WHERE 子句之后 ORDER BY子句之前
缘由在于 语句的执行顺序

select * from 表明 直接得出结果 返回数据

select * from where A=1 先执行where 筛选出需要的记录行 之后再执行 from 得出结果 返回数据

select id from where A=1 group by id 先执行where 筛选出需要的记录行 再使用group by 对记录行进行分组 之后再执行 from 得出结果 返回数据

select id from where A=1 GROUP BY ID ORDER BY ID DESC 先执行where 筛选出需要的记录行 再使用group by 对记录行进行分组 之后再执行 from 得出结果 进行排序 返回数据

*/

--/* 不成立
select vend_id,COUNT(vend_state) from Vendors where count(vend_state)>0 group by vend_id; -- 聚合函数无法用于where 因为 where 是基于行记录进行过滤筛选 。 而聚合函数是对所有记录行进行加载后得出的结果,并不适用与基于每行数据为条件的where
select * from Vendors group by vend_id; -- 查询所得列 在分组语句中并没有进行分组
select vend_name from Vendors group by vend_id; -- 查询所得列 在分组语句中并没有进行分组
select prod_id, COUNT(prod_price) from Products group by prod_price; -- prod_id没有在分组语句中。
--*/

--/* 成立
select COUNT(prod_id) from Products group by prod_name; --查询所得列是聚合函数中的聚集函数 所以可以。
select prod_id from Products group by prod_id; -- 查询所得列在group by 中包含 , 所以可以。
select prod_id, COUNT(prod_price) from Products group by prod_id; -- prod_id 在 GROUP BY 中,并且 prod_price 是聚集函数。 所以可以

--*/

select vend_id,COUNT(vend_state) from Vendors group by vend_id having COUNT(vend_state)>0;

select count(Vendors.vend_state) from Vendors

select DATALENGTH(Vendors.vend_id) from Vendors;

原文地址:https://www.cnblogs.com/java-263/p/13574768.html