Simple and useful SQL scripts (transpose columns and querying the same records in a table)

Source: Internet
Author: User
Tags id3

Exchange of rows and columns CopyCode The Code is as follows: Create Table Test (ID int, name varchar (20), quarter int, profile INT)
Insert into test values (1, 'A', 1,1000)
Insert into test values (1, 'A', 2,2000)
Insert into test values (1, 'A', 3,4000)
Insert into test values (1, 'A', 4,5000)
Insert into test values (2, 'B', 1,3000)
Insert into test values (2, 'B', 2,3500)
Insert into test values (2, 'B', 3,4200)
Insert into test values (2, 'B', 4,5500)
Select * from test
-- Row-to-column Conversion
Select ID, name,
[1] as "first quarter ",
[2] as "Quarter 2 ",
[3] as "three quarters ",
[4] as "fourth quarter ",
[5] as "5"
From
Test
Bytes
(
Sum (profile)
For quarter in
([1], [2], [3], [4], [5])
)
As PVT

Create Table Test2 (ID int, name varchar (20), Q1 int, Q2 int, Q3 int, Q4 INT)
Insert into Test2 values (1, 'A)
Insert into Test2 values (2, 'B', 3000,3500, 4200,5500)
Select * From Test2
-- Column-to-row
Select ID, name, quarter, Profile
From
Test2
Unregister
(
Profile
For quarter in
([Q1], [Q2], [Q3], [Q4])
)
As unpvt

SQL replacement string substring replaceCopy codeThe Code is as follows: -- Example 1:
Update tbpersonalinfo set truename = Replace (truename, substring (truename, 2, 4), '**') Where id = 1
-- Example 2:
Update tbpersonalinfo set mobile = Replace (mobile, substring (mobile,), '********') Where id = 1
-- Example 3:
Update tbpersonalinfo set email = Replace (email, 'chinamobile ',' ******* ') Where id = 1

SQL queries having records of the same table
If an ID can be differentiated, you can write it like this.Copy codeThe Code is as follows: Select * from table where ID in (
Select ID from Table group by ID having sum (1)> 1 ))

If several IDS can be distinguished, you can writeCopy codeThe Code is as follows: Select * from table where id1 + Id2 + ID3 in
(Select id1 + Id2 + ID3 from Table group by id1, Id2, ID3 having sum (1)> 1 ))

Other answers: The data table is zy_bho. I want to find records with the same zyh field name.Copy codeThe Code is as follows: -- Method 1:
Select * From zy_bho A where exists
(Select 1 from zy_bho where [PK] <> A. [PK] And zyh = A. zyh)
-- Method 2:
Select a. * From zy_bho a join zy_bho B
On (A. [PK] <> B. [PK] and A. zyh = B. zyh)
-- Method 3:
Select * From zy_bbo where zyh in
(Select zyh from zy_bbo group by zyh having count (zyh)> 1)
-- The primary key is a primary key or a unique field.

Converts multi-row SQL data into one multi-column data, that is, adding columns.Copy code The Code is as follows: select
Deptname = O. ouname,
'9g' = sum (case when personalgrade = 9 then 1 else 0 end ),
'8g' = sum (case when personalgrade = 8 then 1 else 0 end ),
'7g4 '= sum (case when personalgrade = 7 and jobgrade = 4 then 1 else 0 end ),
'7g3 '= sum (case when personalgrade = 7 and jobgrade = 3 then 1 else 0 end ),
'6g' = sum (case when personalgrade = 6 then 1 else 0 end ),
'5g3 '= sum (case when personalgrade = 5 and jobgrade = 3 then 1 else 0 end ),
'5g2 '= sum (case when personalgrade = 5 and jobgrade = 2 then 1 else 0 end ),
'4g' = sum (case when personalgrade = 4 then 1 else 0 end ),
'3g2 '= sum (case when personalgrade = 3 and jobgrade = 2 then 1 else 0 end ),
'3g1 '= sum (case when personalgrade = 3 and jobgrade = 1 then 1 else 0 end ),
'2' = sum (case when personalgrade = 2 then 1 else 0 end ),
'1g '= sum (case when personalgrade = 1 then 1 else 0 end ),
-- 'Undefined level' = sum (case when personalgrade = NULL then 1 else 0 end)

Table ReplicationCopy codeThe Code is as follows: insert into phonechange_num ([imsi], num)
Select [imsi]
, Count ([IMEI]) as num
From [test]. [DBO]. [phonechange] group by [imsi] Order by num DESC

Syntax 1: insert into table (field1, field2,...) values (value1, value2 ,...)
Syntax 2: insert into Table2 (field1, field2 ,...) select value1, value2 ,... from Table1 (the target table Table2 must exist. Because the target table Table2 already exists, We can insert constants in addition to the fields in the source table table1 .)
Syntax 3: Select vale1, value2 into Table2 from Table1 (it is required that the target table Table2 does not exist because table Table2 is automatically created during insertion and the specified field data in Table1 is copied to table2 .)
Syntax 4: Use the import/export function for full table replication. If you use [write a query to specify the data to be transmitted], then there will be a problem in the replication of big data tables? To a certain extent, the replication will not change, and the memory will burst? It is not written to the table either. Directly executing the preceding three syntaxes will immediately refresh to the database table. You can just refresh the MDF file.

Update data using the update statement with associated subqueriesCopy codeThe Code is as follows: -- Method 1:
Update Table1 set C = (select C from Table2 where a = table1.a) Where C is null
-- Method 2:
Update
Set newqiantity = B. qiantity
From a, B
Where a. bnum = B. bnum
-- Method 3:
Update
(Select a. bnum, A. newqiantity, B. qiantity from a left join B on A. bnum = B. bnum) as C
Set C. newqiantity = C. qiantity
Where C. bnum = xx

Connect to a remote serverCopy codeThe Code is as follows: -- Method 1:
Select * From OpenRowSet ('sqloledb', 'server = 192.168.0.67; uid = sa; Pwd = password', 'select * From bcm2.dbo. tbappl ')
-- Method 2:
Select * From OpenRowSet ('sqloledb', '192. 168.0.67 '; 'sa'; 'Password', 'select * From bcm2.dbo. tbappl ')

Truncate table [Table name]
The following describes the methods and principles of the truncate statement in mssqlserver2000:
Truncate is a SQL statement used to delete data table content. It is used as follows:
The truncate table name is fast and efficient because:
The truncate table function is the same as the delete statement without the WHERE clause: both delete all rows in the table. However, truncate table is faster than delete and uses less system and transaction log resources.
The delete statement deletes a row at a time and records one row in the transaction log. Truncate table deletes data by releasing the data pages used to store table data, and only records the release of pages in transaction logs.
Truncate table deletes all rows in the table, but the table structure, its columns, constraints, and indexes remain unchanged. The Count value used by the new row ID is reset to the seed of the column. To retain the ID Count value, use Delete instead. To delete table definitions and data, use the drop TABLE statement.
For tables referenced by the foreign key constraint, the truncate table cannot be used, but the delete statement without the WHERE clause should be used. Because the truncate table is not recorded in the log, it cannot activate the trigger.
The truncate table cannot be used in the index view.

References
Database Table row-to-column, column-to-row Ultimate Solution

Conversion of rows and columns (Dynamic scripts)

Select into and insert into select table copy statements

Very useful SQL scripts

By: Listening to wind and rain

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.