select * from 后有多个表的使用方法(已知一个表的结构为xxx 怎样通过select语句把他变成以下结构)
Posted shiyusdream
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了select * from 后有多个表的使用方法(已知一个表的结构为xxx 怎样通过select语句把他变成以下结构)相关的知识,希望对你有一定的参考价值。
已知一个表的结构为:
怎样通过select语句把他变成以下结构:
首先,添加数据
USE [DBTEST]
GO
/****** Object: Table [dbo].[SDUDENTS] Script Date: 2019/12/9 10:33:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[SDUDENTS](
[GUID] [int] IDENTITY(100001,1) NOT NULL,
[STUDENT] [nvarchar](50) NOT NULL,
[KEMU] [nvarchar](50) NULL,
[CHENGJI] [int] NULL,
CONSTRAINT [PK_SDUDENTS_1] PRIMARY KEY CLUSTERED
(
[GUID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
SET IDENTITY_INSERT [dbo].[SDUDENTS] ON
GO
INSERT [dbo].[SDUDENTS] ([GUID], [STUDENT], [KEMU], [CHENGJI]) VALUES (100001, N‘李四‘, N‘语文‘, 75)
GO
INSERT [dbo].[SDUDENTS] ([GUID], [STUDENT], [KEMU], [CHENGJI]) VALUES (100002, N‘马六‘, N‘语文‘, 89)
GO
INSERT [dbo].[SDUDENTS] ([GUID], [STUDENT], [KEMU], [CHENGJI]) VALUES (100003, N‘王五‘, N‘语文‘, 67)
GO
INSERT [dbo].[SDUDENTS] ([GUID], [STUDENT], [KEMU], [CHENGJI]) VALUES (100004, N‘张三‘, N‘语文‘, 60)
GO
INSERT [dbo].[SDUDENTS] ([GUID], [STUDENT], [KEMU], [CHENGJI]) VALUES (100005, N‘张三‘, N‘数学‘, 34)
GO
INSERT [dbo].[SDUDENTS] ([GUID], [STUDENT], [KEMU], [CHENGJI]) VALUES (100006, N‘李四‘, N‘数学‘, 79)
GO
INSERT [dbo].[SDUDENTS] ([GUID], [STUDENT], [KEMU], [CHENGJI]) VALUES (100007, N‘王五‘, N‘数学‘, 98)
GO
INSERT [dbo].[SDUDENTS] ([GUID], [STUDENT], [KEMU], [CHENGJI]) VALUES (100008, N‘马六‘, N‘数学‘, 78)
GO
INSERT [dbo].[SDUDENTS] ([GUID], [STUDENT], [KEMU], [CHENGJI]) VALUES (100009, N‘张三‘, N‘英语‘, 88)
GO
INSERT [dbo].[SDUDENTS] ([GUID], [STUDENT], [KEMU], [CHENGJI]) VALUES (100010, N‘李四‘, N‘英语‘, 87)
GO
INSERT [dbo].[SDUDENTS] ([GUID], [STUDENT], [KEMU], [CHENGJI]) VALUES (100011, N‘王五‘, N‘英语‘, 99)
GO
INSERT [dbo].[SDUDENTS] ([GUID], [STUDENT], [KEMU], [CHENGJI]) VALUES (100012, N‘马六‘, N‘英语‘, 54)
GO
SET IDENTITY_INSERT [dbo].[SDUDENTS] OFF
GO
1.先将这个表互相连接查询(需要几个科目就连几次,我这儿有三个科目,所以连3次,SDUDENTS A,SDUDENTS B,SDUDENTS C)
select * from SDUDENTS A,SDUDENTS B,SDUDENTS C
得到以下数据(12*12*12 1728条数据)
2.对表数据进行学生姓名筛选
select * from SDUDENTS A,SDUDENTS B,SDUDENTS C where a.STUDENT=b.STUDENT AND b.STUDENT=c.STUDENT
得到如下数据
3.对科目进行筛选
select * from SDUDENTS A,SDUDENTS B,SDUDENTS C where a.STUDENT=b.STUDENT AND b.STUDENT=c.STUDENT
AND A.KEMU=‘语文‘ AND B.KEMU=‘数学‘ AND C.KEMU=‘英语‘;
得到以下数据
4.定义好查询的内容
select A.STUDENT AS 学生,A.CHENGJI AS 语文,B.CHENGJI AS 数学,C.CHENGJI AS 英语 from SDUDENTS A,SDUDENTS B,SDUDENTS C
where a.STUDENT=b.STUDENT AND b.STUDENT=c.STUDENT
AND A.KEMU=‘语文‘ AND B.KEMU=‘数学‘ AND C.KEMU=‘英语‘;
得到以下数据
新人小白一枚,如果有什么不对的地方望各位大佬多多指点
以上是关于select * from 后有多个表的使用方法(已知一个表的结构为xxx 怎样通过select语句把他变成以下结构)的主要内容,如果未能解决你的问题,请参考以下文章