SQL Server纵表与横表相互转换的方法
编程学习 2021-07-05 13:43www.dzhlxh.cn编程入门
这篇文章主要介绍了SQL Server纵表与横表相互转换的方法,本文通过图文并茂的形式给大家介绍,介绍的非常详细,具有参考借鉴价值,感兴趣的朋友一起看看吧
1,纵表转横表
纵表结构 Table_A:
转换后的结构:
纵表转横表的SQL示例:
SELECT Name , SUM(CASE WHEN Course = N'语文' THEN Grade ELSE 0 END) AS Chinese , SUM(CASE WHEN Course = N'数学' THEN Grade ELSE 0 END) AS Mathematics , SUM(CASE WHEN Course = N'英语' THEN Grade ELSE 0 END) AS English FROM dbo.Table_A GROUP BY Name
2,横表转纵表
横表结构Table_B:
转换后的表结构:
横表转纵表的SQL示例:
SELECT Name , 'Chinese' AS Course , Chinese AS Score FROM dbo.Table_B UNION ALL SELECT Name , 'Mathematics' AS Course , Mathematics AS Score FROM dbo.Table_B UNION ALL SELECT Name , 'English' AS Course , English AS Score FROM dbo.Table_B ORDER BY Name , Course DESC
以上所述是长沙网络推广给大家介绍的SQL Server纵表与横表相互转换的实现方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,长沙网络推广会及时回复大家的。在此也非常感谢大家对狼蚁SEO网站的支持!