Home Database Mysql Tutorial [SQLServer]数据库行列互换

[SQLServer]数据库行列互换

Jun 07, 2016 pm 03:51 PM
sqlserver exchange number database meet interview

面试的时候遇到的数据库SQL问题,没写过,然后研究了一下,现将结果记录下来,方便以后查询。 题目1:将表tbltest1的行列互换 表结构: student kemu fenshu student1 语文 80 student1 数学 90 student1 英语 85 student2 语文 85 student2 数学 92 student

 面试的时候遇到的数据库SQL问题,没写过,然后研究了一下,现将结果记录下来,方便以后查询。

 

题目1:将表tbltest1的行列互换

 

表结构:

student     kemu  fenshu
student1    语文    80
student1    数学    90
student1    英语    85
student2    语文    85
student2    数学    92
student2    英语    82

 

变成:
student  语文    数学   英语
student1   80     90     85
student2   85     92     82

 

SQLserver的sql语句:

declare @sql varchar(4000)  
set @sql = 'select student'  
select @sql = @sql + ',sum(case kemu when '''+ kemu +''' then fenshu else 0 end)['+ kemu+']'
  from (select distinct kemu from tbltest1) as a  
set @sql = @sql + ' from tbltest1 group by student'  
exec(@sql)

或者

select student,sum(case kemu when '语文' then fenshu else 0 end) 语文,sum(case kemu when '数学' then fenshu else 0 end) 数学,sum(case kemu when '英语' then fenshu else 0 end) 英语 from tbltest group by student

 

注:个人觉得上面的好。如果一两个选项可以使用下面的sql,如果选项多上面的sql就显的方便的多。

 

2005的话好像还有个函数可以用,等研究好了再发上来。

 

题目2:合并

 

表结构tbltest2:

id strings
1   my
1   name
1   is

1   xudayu
2   hello
2   world

 

转化成:
id   strings
 1   my name is xudayu 
 2   hello world 

 

SQLServer的sql语句:

 

--创建一个合并的函数  
create function fliehebin(@id int)  
returns varchar(5000)  
as  
begin  
declare @str varchar(5000)  
set @str=''  
select @str=@str + cast(strings as varchar(50)) +' ' from tbltest2 where id=@id  
set @str=subString(@str,1,len(@str))  
return(@str)  
end  
go  
--调用自定义函数得到结果
select distinct id,dbo.fliehebin(id) from tbltest2

 

 

 

 =====================================================================

传说通用的, 如下:

 

 

 

 =====================================================================

 

 

Oracle's:

 

 

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos Jul 18, 2024 am 05:48 AM

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

Detailed tutorial on establishing a database connection using MySQLi in PHP Detailed tutorial on establishing a database connection using MySQLi in PHP Jun 04, 2024 pm 01:42 PM

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

How to handle database connection errors in PHP How to handle database connection errors in PHP Jun 05, 2024 pm 02:16 PM

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

Golang framework interview questions collection Golang framework interview questions collection Jun 02, 2024 pm 09:37 PM

The Go framework is a set of components that extend Go's built-in libraries, providing pre-built functionality (such as web development and database operations). Popular Go frameworks include Gin (web development), GORM (database operations), and RESTful (API management). Middleware is an interceptor pattern in the HTTP request processing chain and is used to add functionality such as authentication or request logging without modifying the handler. Session management maintains session status by storing user data. You can use gorilla/sessions to manage sessions.

How to use database callback functions in Golang? How to use database callback functions in Golang? Jun 03, 2024 pm 02:20 PM

Using the database callback function in Golang can achieve: executing custom code after the specified database operation is completed. Add custom behavior through separate functions without writing additional code. Callback functions are available for insert, update, delete, and query operations. You must use the sql.Exec, sql.QueryRow, or sql.Query function to use the callback function.

How to save JSON data to database in Golang? How to save JSON data to database in Golang? Jun 06, 2024 am 11:24 AM

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

Top 10 Global Digital Virtual Currency Trading Platform Ranking (2025 Authoritative Ranking) Top 10 Global Digital Virtual Currency Trading Platform Ranking (2025 Authoritative Ranking) Mar 06, 2025 pm 04:36 PM

In 2025, global digital virtual currency trading platforms are fiercely competitive. This article authoritatively releases the top ten digital virtual currency trading platforms in the world in 2025 based on indicators such as transaction volume, security, and user experience. OKX ranks first with its strong technical strength and global operation strategy, and Binance follows closely with high liquidity and low fees. Platforms such as Gate.io, Coinbase, and Kraken are at the forefront with their respective advantages. The list covers trading platforms such as Huobi, KuCoin, Bitfinex, Crypto.com and Gemini, each with its own characteristics, but investment should be cautious. To choose a platform, you need to consider factors such as security, liquidity, fees, user experience, currency selection and regulatory compliance, and invest rationally

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

See all articles