Home Database SQL Quietly share 6 SQL query tips

Quietly share 6 SQL query tips

Feb 26, 2021 am 09:57 AM
sql query

Quietly share 6 SQL query tips

Recommended (free): SQL tutorial

1. Row and column conversion

Question: Suppose there is a student score table (tb) as follows:

Quietly share 6 SQL query tips

Want to become (obtain the following results):

Quietly share 6 SQL query tips

Code:

WITH tb(姓名,课程,分数) AS
(
SELECT N'张三',N'语文',74
UNION ALL
SELECT N'张三',N'数学',83
UNION ALL
SELECT N'张三',N'物理',93
UNION ALL
SELECT N'李四',N'语文',79
UNION ALL
SELECT N'李四',N'数学',86
UNION ALL
SELECT N'李四',N'物理',88
)

SELECT 姓名 ,
MAX(CASE 课程 WHEN '语文' THEN 分数 ELSE 0 END) 语文,
MAX(CASE 课程 WHEN '数学' THEN 分数 ELSE 0 END) 数学,
MAX(CASE 课程 WHEN '物理' THEN 分数 ELSE 0 END) 物理
FROM tb GROUP BY  姓名
Copy after login

2. Paging

Option 1: Use the NOT IN and SELECT TOP paging statement forms

SELECT TOP 10 * FROM TestTable
WHERE ID NOT IN
(SELECT TOP 20 ID FROM TestTable ORDER BY ID)
ORDER BY ID
Copy after login

Option 2: Use the ID greater than and SELECT TOP paging statement form

SELECT TOP 10 * FROM TestTable
WHERE ID > (
SELECT MAX(id) FROM 
(SELECT TOP 20 id FROM 
TestTable ORDER BY id) AS T)
ORDER BY ID
Copy after login

Option 3: Use the feature ROW_NUMBER in SQL Server for paging

SELECT * FROM (
  SELECT ROW_NUMBER() OVER(ORDER BY ID DESC) AS ROWID,*
  FROM TestTable
) AS mytable where ROWID between 21 and 40
Copy after login

3. Merge results

Merge duplicates Rows

 SELECT * FROM A
UNION
SELECT * FROM B
Copy after login

Do not merge duplicate rows

SELECT * FROM A
UNION ALL
SELECT * FROM B
Copy after login

4. Random sorting

SELECT * FROM TestTable ORDER BY NEWID()
Copy after login

can also be combined with TOP Random first N records

SELECT TOP 100 * FROM TestTable ORDER BY NEWID()
Copy after login

5. Separate the data on both sides with any symbol

For example, if we use commas (,) to separate the data, it will be as follows The data

Quietly share 6 SQL query tips

is divided into as shown below:

Quietly share 6 SQL query tips

SELECT R,
CASE WHEN  CHARINDEX(',',R)>1 THEN  LEFT(R,CHARINDEX(',',R)-1) ELSE NULL END AS R1 ,
CASE WHEN CHARINDEX(',',R)>1 THEN RIGHT(R,(LEN(R) - CHARINDEX(',',R))) ELSE NULL END AS R2
FROM  t
Copy after login

The code is long, we split the code Understanding:

SELECT  CHARINDEX(',',',') --结果是1
SELECT  CHARINDEX(',','NULL') --结果是0
SELECT  CHARINDEX(',','') --结果是0
SELECT  CHARINDEX(',','A,B') --结果是2
SELECT  LEN('A,B') --结果是3
SELECT  LEN('A,B') - CHARINDEX(',','A,B') --结果是3-2=1
SELECT  RIGHT('A,B',( LEN('A,B') - CHARINDEX(',','A,B'))) --结果是 B
Copy after login

In the last step, we split 'A, B' into B. Similarly, we can also obtain A using a similar method.

6. WAITFOR delayed execution

For example, wait for 1 hour, 2 minutes and 3 seconds before executing the SELECT statement

WAITFOR DELAY '01:02:03'
SELECT * FROM Employee
Copy after login

DELAY is the delay before execution starts.

Example: Wait until 11:08 pm before executing the SELECT statement

WAITFOR TIME '23:08:00'
SELECT * FROM Employee
Copy after login

TIME is to wait until a specific time to start execution

我是岳哥,最后给大家分享我写的SQL两件套:《SQL基础知识第二版》和《SQL高级知识第二版》的PDF电子版。里面有各个语法的解释、大量的实例讲解和批注等等,非常通俗易懂,方便大家跟着一起来实操。有需要的读者可以下载学习,在下面的公众号「数据前线」(非本号)后台回复关键字:SQL,就行数据前线
——End——

后台回复关键字:1024,获取一份精心整理的技术干货
后台回复关键字:进群,带你进入高手如云的交流群。
推荐阅读
27岁发明SQL以后,上帝把他带走了

微信8.0不好玩?那可能是你打开方式不正确!

一个员工的离职成本有多恐怖!
SQL养成这些好习惯是一笔财富
MySQL基本知识点梳理和查询优化
Copy after login

More related free learning recommendations: SQLserver

The above is the detailed content of Quietly share 6 SQL query tips. For more information, please follow other related articles on the PHP Chinese website!

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)

Meituan interview question: Have you ever encountered slow SQL? How was it solved? Meituan interview question: Have you ever encountered slow SQL? How was it solved? Aug 24, 2023 pm 03:41 PM

MySQL's slow query log is a log record provided by MySQL. It is used to record statements in MySQL whose query time exceeds (greater than) the set threshold (long_query_time) and records them in the slow query log.

PHP and PDO: How to execute complex SQL queries PHP and PDO: How to execute complex SQL queries Jul 28, 2023 pm 03:43 PM

PHP and PDO: How to execute complex SQL query statements When processing database operations, PHP provides a powerful extension library PDO (PHPDataObjects) to simplify interaction with the database. PDO supports a variety of databases, such as MySQL, SQLite, etc., and also provides a wealth of functions and methods to facilitate developers to perform various database operations. This article will introduce how to use PDO to execute complex SQL query statements, and attach corresponding code examples. Connect to the database

What are the common table operations in PHP programming? What are the common table operations in PHP programming? Jun 12, 2023 am 09:46 AM

In web development, tables are the most basic and commonly used elements, and PHP is a popular server-side programming language. There are many common techniques and methods in table operations. This article will introduce common table operations in PHP programming. Displaying data tables In PHP, you can use the table tag in HTML to display data tables. It is worth noting that the table must be generated in a PHP script. Here is an example of a basic HTML table tag: <table><tr>

PHP query statement usage example PHP query statement usage example Mar 23, 2024 am 11:27 AM

PHP is a powerful server-side scripting language that is widely used in web development. In web development, we often need to interact with the database and execute query statements to obtain data. This article will introduce you to how to write query statements and usage examples in PHP. 1. Connect to the database Before using PHP to query the database, you first need to establish a connection with the database. Generally, we will use the MySQL database as an example. The code to connect to the database is as follows: $servername=

Why does my Go program error when executing SQL queries? Why does my Go program error when executing SQL queries? Jun 09, 2023 pm 06:10 PM

In Go programming, using SQL queries is a common task. However, sometimes errors occur when executing SQL queries, causing the program to fail to execute correctly. In order to solve these errors, we need to have a deep understanding of how SQL queries and the Go language interact. Below are some possible errors and corresponding solutions. Lack of database driver In Go language, you need to use a specific database driver to connect and operate the database. If you try to perform a database query and the database driver is not properly installed and configured

Most SQL query efficiency optimization practices in PHP programming Most SQL query efficiency optimization practices in PHP programming Jun 23, 2023 am 10:37 AM

With the development of network technology, PHP programming has become the mainstream of website development for many companies. In PHP programming, SQL query efficiency is an issue that requires every programmer to pay attention and deal with. Inefficient SQL query will lead to slow website response, high system load or other unfriendly effects. Therefore, this article will focus on introducing various SQL query efficiency optimization practices in PHP programming to improve the execution efficiency of the program and the response speed of the entire system. Database index Database index is a basic method to improve the speed of database query

How to optimize SQL query statements and index usage in PHP development? How to optimize SQL query statements and index usage in PHP development? Nov 02, 2023 pm 12:12 PM

How to optimize SQL query statements and index usage in PHP development? In PHP development, database query is a very common operation. However, when the amount of data increases, query performance may be affected, causing the application to slow down. In order to improve query performance, we need to optimize the use of SQL query statements and indexes. This article will introduce some optimization tips and best practices to help you improve SQL query performance in PHP development. 1. Use the correct index: Index is an important part of the database to improve query performance. in design data

How to deal with SQL query errors in PHP language development? How to deal with SQL query errors in PHP language development? Jun 09, 2023 pm 06:13 PM

PHP language is a commonly used server-side scripting language used in fields such as website development. In PHP language development, SQL query is a common operation, but due to various reasons, SQL query may cause errors. Therefore, developers need to handle these errors in their code to ensure the stability and correctness of the application. Generally speaking, there are several common ways to handle SQL query errors in PHP language: 1. Use try/catch block to handle exceptions. In PHP language, you can use try/catch

See all articles