Exquisite SQL Statements page 1/2

Source: Internet
Author: User

Note: copy a table (only copy structure, source table name: a new table name: B)
Select * into B from a where 1 <> 1

Description: copy a table (copy data, source table name: A target table name: B)
Insert into B (a, B, c) Select D, E, F from B;

Note: DisplayArticle, Submitted and last reply time
Select a. Title, A. username, B. adddate from Table A, (select max (adddate) adddate from table
Where table. Title = A. Title) B

Description: External join query (table name 1: Table A name 2: B)
Select a. a, a. B, A. C, B. C, B. D, B. F from a left out join B on A. A = B. C

Note: Five minutes in advance of the schedule
Select * from Schedule where datediff ('minute ', F Start Time, getdate ()> 5

Note: Two associated tables are used to delete information that is already unavailable to the primary table in the secondary table.
Delete from info where not exists (select * From infobz where info. INFID = infobz. INFID)

Note :--

SQL:

Select a. Num, A. Name, B. upd_date, B. prev_upd_date

From Table1,

(Select X. Num, X. upd_date, Y. upd_date prev_upd_date

From (select num, upd_date, inbound_qty, stock_onhand

From Table2

Where to_char (upd_date, 'yyyy/mm') = to_char (sysdate, 'yyyy/mm') X,

(Select num, upd_date, stock_onhand

From Table2

Where to_char (upd_date, 'yyyy/mm') =

To_char (to_date (to_char (sysdate, 'yyyy/mm') | '/01', 'yyyy/MM/dd')-1, 'yyyy/mm ')) y,

Where X. num = Y. Num (+)

And X. inbound_qty + nvl (Y. stock_onhand, 0) <> X. stock_onhand) B

Where a. num = B. Num

Note :--
Select * From studentinfo where not exists (select * from student where
Studentinfo. ID = student. ID) and Department name = '"& strdepartmentname &"' and professional name
= '"& Strpolicsionname &" 'order by gender, student origin, total score of the College Entrance Examination

Go to the telephone fee statistics of each unit from the database for one year (two sources of the fixed telephone fee congratulation fertilizer List)

Select a. userper, A. Tel, A. standalone, to_char (A. telfeedate, 'yyyy') as telyear,

Sum (decode (to_char (A. telfeedate, 'mm'), '01', A. factration) as Jan,

Sum (decode (to_char (A. telfeedate, 'mm'), '02', A. factration) as Fri,

Sum (decode (to_char (A. telfeedate, 'mm'), '03', A. factration) as MAR,

Sum (decode (to_char (A. telfeedate, 'mm'), '04 ', A. factration) as Apr,

Sum (decode (to_char (A. telfeedate, 'mm'), '05 ', A. factration) as may,

Sum (decode (to_char (A. telfeedate, 'mm'), '06', A. factration) as Jue,

Sum (decode (to_char (A. telfeedate, 'mm'), '07 ', A. factration) as Jul,

Sum (decode (to_char (A. telfeedate, 'mm'), '08 ', A. factration) as Agu,

Sum (decode (to_char (A. telfeedate, 'mm'), '09', A. factration) as SEP,

Sum (decode (to_char (A. telfeedate, 'mm'), '10', A. factration) as Oct,

Sum (decode (to_char (A. telfeedate, 'mm'), '11', A. factration) as Nov,

Sum (decode (to_char (A. telfeedate, 'mm'), '12', A. factration) as Dec

From (select a. userper, A. Tel, A. standalone, B. telfeedate, B. factration

From telfeestand A, telstmb

Where a. Tel = B. telfax)

Group by A. userper, A. Tel, A. standalone, to_char (A. telfeedate, 'yyyy ')

Notes: Four-table join query Problems
Select * from a left inner join B on A. A = B. B right inner join C on A. A = C inner join D on
A. A = D. D where .....

Note: Obtain the smallest unused ID number in the table.

Select (case when exists (select * From handle B where B. handleid = 1) Then min (handleid) + 1
Else 1 end) as handleid from handle where not handleid in (select a. handleid-1 from
Handle)

A problem with an SQL statement: column and column Conversion
Select * From v_temp
The preceding view result is as follows:
User_name role_name
-------------------------
System Administrator
Feng Administrator
Feng users
Test Users
The result is as follows:
User_name role_name
---------------------------
System Administrator
Feng administrator, general user
Test Users
==============================
Create Table a_test (name varchar (20), role2 varchar (20 ))
Insert into a_test values ('lil', 'admin ')
Insert into a_test values ('zhang', 'admin ')
Insert into a_test values ('zhang', 'average user ')
Insert into a_test values ('change', 'General user ')

Create Function join_str (@ content varchar (100 ))
Returns varchar (2000)
As
Begin
Declare @ STR varchar (2000)
Set @ STR =''
Select @ STR = @ STR + ',' + rtrim (role2) from a_test where [name] = @ content
Select @ STR = right (@ STR, Len (@ Str)-1)
Return @ Str
End
Go

-- Call:
Select [name], DBO. join_str ([name]) role2 from a_test group by [name]

-- Select distinct name, DBO. uf_test (name) from a_test

Quickly compare two tables with the same structure
For two tables with the same structure, one table has about 30 thousand records and one table has about 20 thousand records. How can I quickly find different records of the two tables?
======================================
Here is a test method for getting data from the orders table in northwind.
Select * into N1 from orders
Select * into N2 from orders

Select * from N1
Select * from N2

-- Add a primary key and modify several entries of several fields in N1.
Alter table N1 add constraint pk_n1_id primary key (orderid)
Alter table N2 add constraint pk_n2_id primary key (orderid)

Select orderid from (select * from N1 Union select * from N2) a group by orderid having
Count (*)> 1

Yes, and the IDs of different records are displayed.
The following applies to situations where both parties record the same,

Select * from N1 where orderid in (select orderid from (select * from N1 Union select * from
N2) a group by orderid having count (*)> 1)
Records that do not exist between the two parties are better handled.
-- Delete several records in N1 and N2
Delete from N1 where orderid in ('20140901', '20160901 ')
Delete from N2 where orderid in ('20140901', '20160901 ')

--*************************************** **********************
-- Both parties have this record but are not exactly the same
Select * from N1 where orderid in (select orderid from (select * from N1 Union select * from
N2) a group by orderid having count (*)> 1)
Union
-- If N2 exists but does not exist in N1, it is stored in, limit 30.
Select * from N1 where orderid not in (select orderid from N2)
Union
-- N1.
Select * from N2 where orderid not in (select orderid from N1)

Four methods to obtain n to M records in the table:

1.
Select top M * into temporary table (or table variable) from tablename order by columnname -- insert top M pen
Set rowcount n
Select * from Table variable order by columnname DESC

2.
Select Top N * from (select top M * From tablename order by columnname) A order
Columnname DESC

3. If there are no other identity columns in tablename, then:
Select Identity (INT) id0, * into # temp from tablename

N to M statements:
Select * from # temp where id0> = N and id0 <= m

If you report an error when executing the Select Identity (INT) id0, * into # temp from tablename statement, it is because
If the select into/bulkcopy attribute in the middle of your DB is not enabled, you must first execute:
Exec sp_dboption your DB name, 'select into/bulkcopy', true

4. If the table contains the identity attribute, it is simple:
Select * From tablename where identitycol between N and m

How do I delete repeated records in a table?
Create Table a_dist (ID int, name varchar (20 ))

Insert into a_dist values (1, 'abc ')
Insert into a_dist values (1, 'abc ')
Insert into a_dist values (1, 'abc ')
Insert into a_dist values (1, 'abc ')

Exec up_distinct 'A _ dist', 'id'

Select * From a_dist

Create procedure up_distinct (@ t_name varchar (30), @ f_key varchar (30 ))
-- F_key indicates the group field, that is, the primary key field.
As
Begin
Declare @ Max integer, @ ID varchar (30), @ SQL varchar (7999), @ type Integer
Select @ SQL = 'maid cur_rows cursor for select' + @ f_key + ', count (*) from' + @ t_name +'
Group by '+ @ f_key + 'having count (*)> 1'
Exec (@ SQL)
Open cur_rows
Fetch cur_rows into @ ID, @ Max
While @ fetch_status = 0
Begin
Select @ max = @ max-1
Set rowcount @ Max
Select @ type = xtype from syscolumns where id = object_id (@ t_name) and name = @ f_key
If @ type = 56
Select @ SQL = 'delete from' + @ t_name + 'where' + @ f_key + '=' + @ ID
If @ type = 167
Select @ SQL = 'delete from' + @ t_name + 'where' + @ f_key + '=' + ''' + @ ID + ''''
Exec (@ SQL)
Fetch cur_rows into @ ID, @ Max
End
Close cur_rows
Deallocate cur_rows
Set rowcount 0
End

Select * From policypes
Select * From syscolumns where id = object_id ('A _ dist ')

Maximum sorting of query data (only one statement can be used for writing)
Create Table hard (qu char (11), Co char (11), je numeric (3, 0 ))

Insert into hard values ('A', '1', 3)
Insert into hard values ('A', '2', 4)
Insert into hard values ('A', '4', 2)
Insert into hard values ('A', '6', 9)
Insert into hard values ('B', '1', 4)
Insert into hard values ('B', '2', 5)
Insert into hard values ('B', '3', 6)
Insert into hard values ('C', '3', 4)
Insert into hard values ('C', '6', 7)
Insert into hard values ('C', '2', 3)

The query results are as follows:

Qu Co je
---------------------------
A 6 9
A 2 4
B 3 6
B 2 5
C 6 7
C 3 4

Group by Qu. In each group, the first two digits of JE are the largest !!
Only one SQL statement can be used !!!
Select * from hard a where je in (select Top 2 je from hard B where a. Qu = B. Qu order by je)

Are you sure you want to delete the SQL statement for Repeated Records?
How to delete a record with the same field, leaving only one record.
For example, the table test contains the ID and name fields.
If there are records with the same name, only one record is left, and the remaining records are deleted.
The content of the name is not fixed, and the number of identical records is not fixed.
Is there such an SQL statement?
====================================
A: a complete solution:

Record duplicate records in the temp1 table:
Select [flag field ID], count (*) into temp1 from [Table name]
Group by [flag field ID]
Having count (*)> 1

2. Record non-Repeated Records in Table temp1:
Insert temp1 select [flag field ID], count (*) from [Table name] group by [flag field ID] Having count (*)
= 1

3. Create a table that contains all non-Repeated Records:
Select * into temp2 from [Table name] where flag field ID in (select flag field ID from temp1)

4. Delete duplicate tables:
Delete [Table name]

5. Restore table:
Insert [Table name] Select * From temp2

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.