--首先创建数据库TEST
CREATE DATABASE TEST
--创建表tb_user
USE TEST
CREATE TABLE [tb_user](
[name] [nvarchar] (50) NOT NULL,
[age] [int] NOT NULL,
[sex] [nvarchar] (4)
)
--表中插入测试数据
USE TEST
INSERT INTO [dbo].[tb_user] (name,age,sex) values('张三','18','男')
INSERT INTO [dbo].[tb_user] (name,age,sex) values('李斯','19','男')
INSERT INTO [dbo].[tb_user] (name,age,sex) values('校花','18','女')
INSERT INTO [dbo].[tb_user] (name,age,sex) values('校草','20','男')
INSERT INTO [dbo].[tb_user] (name,age,sex) values('张三2','19','男')
INSERT INTO [dbo].[tb_user] (name,age,sex) values('张小花','19','女')
--查询
SELECT * FROM TB_USER
--根据年龄排序(升序 ASC 降序DESC)升序中ASC可以不写
SELECT * FROM TB_USER ORDER BY AGE DESC
--根据性别统计人数
SELECT SEX,COUNT(*) AS P_NUM FROM TB_USER GROUP BY SEX
--查询性别为男的用户详细
SELECT NAME,AGE,SEX FROM TB_USER WHERE SEX='男'
--查询用户中最大年龄
SELECT MAX(AGE) FROM TB_USER
--查询用户中最小年龄
SELECT MIN(AGE) FROM TB_USER
--查询最大年龄的用户(最小同理将MAX函数换为MIN)
SELECT * FROM TB_USER WHERE AGE=(SELECT MAX(AGE) FROM TB_USER)
--求男女平均年龄
SELECT SEX, AVG(AGE) AS AVG_AGE FROM TB_USER GROUP BY SEX
--根据年龄统计人数
SELECT AGE,COUNT(*) AS NUM FROM TB_USER GROUP BY AGE
--查询姓张的男女人数
SELECT SEX,COUNT(*) AS NUM FROM TB_USER WHERE NAME LIKE'张%' GROUP BY SEX
--查询姓张的男女人数行列转换
SELECT
CASE SEX WHEN '男' THEN COUNT(*) ELSE 0 END AS 男,
CASE SEX WHEN '女' THEN COUNT(*) ELSE 0 END AS 女
FROM TB_USER WHERE NAME LIKE '张%' GROUP BY SEX