SQL查询语句
如何从使用 SQL(如果可能的话,使用 MYsql 和 MS Access)更改为
SID Name Math English French
1 Sam 16 17 19
2 Tom 18 14 12
3 Al 90 33 2
:
SID subject Mark
1 Math 16
1 English 17
1 French 19
2 Math 18
2 English 14
2 French 12
3 Math 90
3 English 33
3 French 2
使用 SQL?
谢谢。
How can I change from
SID Name Math English French
1 Sam 16 17 19
2 Tom 18 14 12
3 Al 90 33 2
to:
SID subject Mark
1 Math 16
1 English 17
1 French 19
2 Math 18
2 English 14
2 French 12
3 Math 90
3 English 33
3 French 2
using SQL (MYsql and MS Access if possible) ?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
但问题的根本原因是错误的数据库设计。这些主题首先不应该是列,而应该存储在与您所需的输出非常相似的表中。
编辑
那么它有什么作用呢?
返回
sid
列,这是一个“虚拟”列,其硬编码值'Math'
的名称为subject
。由于您尚未将值'Math'
存储在某处,因此必须对其进行硬编码。最后,它还使用名称mark
选择列math
。请注意math
和'Math'
之间的区别 - 一个是列,另一个是字符串文字,因为有单引号。这是针对所有三个主题完成的(如果您有四个主题,则需要 UNION 中的四个部分)
UNION ALL 将所有三个 SELECT 合并到一个查询中。 andr 解决方案(已被不理解它的人否决)通过明确地将其放入派生表(或内联视图)中使这一点变得更加清晰。
单独运行每个 SELECT 以查看各个部分正在做什么。
as mark
部分称为“列别名”,也可用于从连接中的不同表中检索具有相同名称的列,并且在结果集中仍然具有唯一的名称。But the root cause of your problem is a wrong database design. Those subjects shouldn't be columns in the first place and should be stored in a table very much like your desired output.
Edit
So what does it do?
Returns the
sid
column, a "virtual" column with the hardcoded value'Math'
that is given the namesubject
. As you have not stored the value'Math'
somewhere, this had to be hardcoded. Then at last it also selects the columnmath
using the namemark
instead. Note the difference betweenmath
and'Math'
- one is a column the other one a string literal because of the single quotes.This is done for all three subjects (if you had four subjects, you'd need four parts in the UNION)
The UNION ALL combines all three SELECTs into one single query. andr solution (which has been downvoted by someone who didn't understand it) makes this even clearer by explicitely putting that into a derived table (or inline view).
Run each SELECT on its own to see what the individual parts are doing.
The part
as mark
is called a "column alias" and can also be used to retrieve columns with the same name from different tables in a join and still have unique names in the result set.试试这个:
Try this:
使用数据透视表:
http://www.ehow.com/i/#article_5336679
希望这有帮助
Use a pivot table:
http://www.ehow.com/i/#article_5336679
Hope this helps
在 SQL Server 2005 或更高版本中,您可以使用 UNPIVOT:
In SQL Server 2005 or higher you can use UNPIVOT:
应该做的伎俩
Should do the trick
其中表=
where table =