0% found this document useful (0 votes)
41 views34 pages

Advanced SQL (Draft)

The document describes four techniques for advanced SQL queries: 1) filtering the latest record, 2) transposing fields from vertical to horizontal, 3) concatenating records into one using For XML Path, and 4) using pivot tables. Technique 1 demonstrates filtering a table to return the latest record for each item by joining on the primary key and maximum date. Technique 2 shows transposing vertically stored data into horizontal columns using case statements. Examples are provided for each technique.

Uploaded by

Trần Đạt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views34 pages

Advanced SQL (Draft)

The document describes four techniques for advanced SQL queries: 1) filtering the latest record, 2) transposing fields from vertical to horizontal, 3) concatenating records into one using For XML Path, and 4) using pivot tables. Technique 1 demonstrates filtering a table to return the latest record for each item by joining on the primary key and maximum date. Technique 2 shows transposing vertically stored data into horizontal columns using case statements. Examples are provided for each technique.

Uploaded by

Trần Đạt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 34

Advanced SQL for P5

Common Query Techniques

Exclusively for P5
Jun-2018
Agenda
Technique 1 Filtering the lastest update or record

Technique 2 Transposing field from vertical to horizontal shape

Technique 3 Using For XML Path to concatenate records into one

Technique 4 Using pivot table in SQL


Technique 1 Filtering the lastest update or record

Ask: Which row is the latest record of each coil (A, B, C)?

How do you
Item Value Record date
know?
Coil A 10 2018-01-31
Coil A 20 2018-02-28
Coil A 30 2018-03-31
Coil B 20 2018-01-01
Coil B 15 2018-01-15
Coil C 45 2018-05-01
Technique 1 Filtering the lastest update or record

Basic logic

[2] Join Table [A]


[1] Get the Table [A’] (All of fields)
Table [A] [Primary field]
(All of fields) lastest ones &
Max(DateTime)

Table [A’’]
[Primary field] &
Max(DateTime) &
All of fields
Technique 1 Filtering the lastest update or record
Basic SQL syntax

SELECT
<A2> Optional fields
FROM
(
SELECT A.[Primary field], Max(A.DateTime) AS <DateTime>
FROM

( Select [Primary field] , [Record date]++[Record time] as [DateTime] From [Table A]) as <A>

[ WHERE <search_condition> ]

GROUP BY A.[Primary field]

) as <A1>
INNER JOIN
[Table A] as <A2> ON ( A1.[Primary field] = A2.[Primary field]
and A1.[DateTime]=A2.[Recorde date]++A2.[Record time])
Technique 1 Filtering the lastest update or record

Example: Below is the SQL syntax to get tensile test for coil no. ('141326','240069','2699431’), but each coil had been conducted 2-3 times.
Please get the newest record for them.

SELECT
ha.Productcoilno,ha.Sampleid,
ha.ysresult YS,
ha.tsresult TS,
ha.elresult EL,
ha.createdate, ha.createtime
FROM db.tbtqha ha
WHERE 1=1
and ha.Productcoilno in ('141326','240069','2699431')
and ha.official='Y’

Productcoilno Sampleid YS TS EL Createdate Createtime


141326 KECC1146370 193 322 46 20141222 013805
141326 KECC1146380 194 326 45 20141222 015224
141326 KQ12QC002700 194 326 45 20141224 114616
240069 KEAG1785690 349 403 32 20171002 194821
240069 KQ11QC010770 349 403 32 20171109 144950
240069 KQAG1785690 346 404 33 20180319 215130
2699431 KE5G1967180 0 0 0 20180504 132238
Technique 1 Filtering the lastest update or record
COILNO SAMPLEID YS TS EL CREATEDATE CREATETIME
Answer 141326 KQ12QC002700 194 326 45 20141224 114616
240069 KQAG1785690 346 404 33 20180319 215130
2699431 KQ05QC011770 261 353 40 20180507 083639
SELECT
A2.PRODUCTCOILNO AS COILNO,
A2.SAMPLEID,
A2.YSRESULT YS,
A2.TSRESULT TS,
A2.ELRESULT EL,
A2.CREATEDATE,
A2.CREATETIME
FROM
(
SELECT A.PRODUCTCOILNO, max(A.datetime) DATETIME
FROM
(select PRODUCTCOILNO, CREATEDATE++CREATETIME AS DATETIME FROM DB.TBTQHA) AS A

GROUP BY A.PRODUCTCOILNO
) AS A1

LEFT JOIN DB.TBTQHA A2 ON A1.PRODUCTCOILNO=A2.PRODUCTCOILNO AND A1.DATETIME=A2.CREATEDATE++A2.CREATETIME

WHERE A2.OFFICIAL='Y'
AND A1.PRODUCTCOILNO IN ('141326','240069','2699431')
Technique 1 Filtering the lastest update or record

Practice
Get the latest Defect of coil no. (2540541, 142146, 1814305)
Given tables:
DB.TBICDEFECT,
DB.TBICCOMPDO,
DB.TBICPATH
Result
Coil
Item Coil No. Defect 1 Defect 2 Defect 3
Status
1142146 50 T110-NAC-3-99 : 6.5/700;4/350;5.5/600 T250-NAD-3-60 : 0.5MM N16A-NAD-3-60 : DA CAT UNDER WIDTH
21814305 50 T33C-DRN-3-20 : Z260-NHL-3-01 : ---00 :
32540541 50 NB20-DAN-5-90 : C80B-TDN-5-30 : ---00 :
Technique 2 Transposing field from vertical to horizontal
Idea

Item Criteria Value Item X Y Z


Coil A 85 50 90
Coil A X 85
Coil B 70 75 -
Coil A Y 50 ose
n sp Coil C 95 - -
Coil A Z 90 Tra
Coil B X 70
Coil B Y 75
Coil C X 95
Technique 2 Transposing field from vertical to horizontal

Basic logic
Max(Z)
Max(Y)

Max(X)
Primary Criteria Value Case…when Primary X Y Z
Coil A X a Case…when Coil A a 0 0 Primary X Y Z
Coil A Y b Case…when Coil A 0 b 0 Coil A a b c
Coil A Z c Coil A 0 0 c
Technique 2 Transposing field from vertical to horizontal
Basic SQL syntax

SELECT
B.[Primary field],
Max(B. Xi) as [Xi]

FROM
(
Select A.[Primary field],
Case when A.[Criteria]=‘Xi’ then A.Value Else ‘0’ end as [Xi]
From [Table A] as [A]
) as [B]

[ WHERE <search_condition> ]
GROUP BY B.[Primary field]
Technique 2 Transposing field from vertical to horizontal

Example: Compose a SQL syntax to get Chemical element (C, Mn, Si, P, S) for coil
no. ('141326','240069','2699431’) following table below
Given tables: DB.TBTQ03, DB.TBIHAMA01

Coil No. Heat No. C Mn Si P S


141326 4B52010 0.04 0.17 0.007 0.015 0.004
240069 4EL29 0.04 0.49 0.01 0.015 0.002
2699431 30271 0.047 0.19 0.01 0.011 0.005
Technique 2 Transposing field from vertical to horizontal
Answer

SELECT
IH.coilNo, B.heatNo,
max(B.C) as C, max(B.Mn) as Mn, max(B.Si) as Si, Max(B.P) as P, Max(B.S) as S

FROM
(
select
a.heatNo,
case when a.element='C’ then a.testvalue else '0' end C,
case when a.element='Mn’ then a.testvalue else '0' end Mn,
case when a.element='Si’ then a.testvalue else '0' end Si,
case when a.element='P’ then a.testvalue else '0' end P,
case when a.element='S’ then a.testvalue else '0' end S

from DB.TBTQ03 as A
) as B left join DB.TBIHAMA01 IH on IH.HEATNO=B.HEATNO

WHERE IH.COILNO IN ('141326','240069','2699431')


Technique 2 Transposing field from vertical to horizontal
Practice
From the given table DB.TBPOCORE01HRSPEC, write a SQL syntax to get the data for these order '201610LA0003’, '201610LA0007’,
'201806TESTCG’ following table below:
Order No. Item No hrthkaim hrwthaim CSC HR spec NSSMC HR Spec FHS HR Spec
201610LA0003 001 4.8 1547 CSVC HR 1006-1(FOR CG-CQ1) CNGSPC-1
201610LA0003 002 4.5 1238 CSVC HR 1006-1(FOR CG-CQ1) CNGSPC-1
201610LA0003 003 4.5 1548 CSVC HR 1006-1(FOR CG-CQ1) CNGSPC-1
201610LA0003 004 4.8 1242 CSVC HR 1006-1(FOR CG-CQ1) CNGSPC-1
201610LA0007 001 3.8 1239 CSVC HR 440-1(FOR CG)
201610LA0007 002 4 1239 CSVC HR 1006-1(FOR CG-CQ1) CNGSPC-1
201610LA0007 003 3.6 1239 CSVC HR 1006-1(FOR CG-CQ1) CNGSPC-1
201610LA0007 004 2.8 936 CSVC HR 1006-1(FOR CG-CQ1) CNGSPC-1
201806TESTCG 001 2.9 1237 CSVC HR 1022-2
201806TESTCG 002 2.3 1240 CSVC HR 1022-2
201806TESTCG 003 4.5 1275 CSVC HR 340-1(FOR CG)
201806TESTCG 004 4 1271 CSVC HR 440-1(FOR CG)
201806TESTCG 005 4.5 1270 CSVC HR 490-1 (FOR CG)
201806TESTCG 006 3.8 1272 CSVC HR 490-1 (FOR CG)
201806TESTCG 007 2.1 1273 CSVC HR 490-1 (FOR CG)
201806TESTCG 008 2.6 1271 CSVC HR 1004-1(FOR CG-CQS) CNG270C-1 F1004-1(FOR CG-CQS)
201806TESTCG 009 3.6 1272 CSVC HR 1004-1(FOR CG-CQS) CNG270C-1 F1004-1(FOR CG-CQS)
201806TESTCG 010 4 1272 CSVC HR 1004-1(FOR CG-CQS) CNG270C-1 F1004-1(FOR CG-CQS)
201806TESTCG 011 4.5 1271 CSVC HR 1004-1(FOR CG-CQS) CNG270C-1 F1004-1(FOR CG-CQS)
201806TESTCG 012 4.8 1271 CSVC HR 1004-1(FOR CG-CQS) CNG270C-1 F1004-1(FOR CG-CQS)
201806TESTCG 013 2.6 1123 CSVC HR 1006-1(FOR CG-CQ1) CNGSPC-1 F1006-1(FOR CG-CQ1)
Technique 3 Using For XML Path to concatenate records into
one

XML Path
For
Stuff

Grouping into one line?

HOW?
Technique 3 Using For XML Path to concatenate records into
one
a) What’s XML?
XML: eXtensible Markup Language
Basic syntax of XML
<element name Attributes=“Value">content</element name>
Or can be simplified

<element name>content</element name>

Purpose
XML was designed to store and transport data.
XML was designed to be both human- and machine-readable.
Example
<Company>CSVC Employee=“800“ Department=“9"</Company>

<Company>CSVC</Company>
Technique 3 Using For XML Path to concatenate records into
one
What’s FOR XML PATH?
FOR XML has 4 modes: RAW, AUTO, EXPLICIT, PATH.
This topic focuses on PATH mode
The basic syntax
SELECT [Field1], [Field2], ...
FROM [table_name]
WHERE [Search condition];
FOR XML PATH(‘’)

Result

<Field1>Value</Field1><Field2>Value</Field2><Field1>Value</Field1><Field2>Value</Field2>…
Technique 3 Using For XML Path to concatenate records into
one
b) What’s STUFF function?
The STUFF function inserts a string into another string.
Step 1: It deletes a specified length of characters in the first string at the start position
Step 2: and then inserts the second string into the first string at the start position.

STUFF ( first string, start , length , second string)


Example

Stuff(‘Quality’,4,1,‘nt’)

Result: Quantity
Technique 3 Using For XML Path to concatenate records into
one
c) Combine For XML Path(‘’) & Stuff
---Create a table
Declare @P5 as table
(
Section varchar(3),
Name varchar(10)
)
INSERT INTO @P5 values
('P51’,N'Giang'),('P51',N'Tai'),('P51',N'My'),('P51',N'VPhuc'),('P51',N'Khoi'),
('P51',N'Tan’),
('P51',N'TTrang'),('P51',N'Dien'),('P51',N'TPhuong'), ('P52',N'MPhuong'),
('P52',N'TPhuc'),('P52',N'Hoa'),('P52',N'Cuong'),('P52',N'Vien'),('P52',N'DTrang’), ('P53',N'BLong'),
('P53',N'Manh'),('P53',N'Tho'),('P53',N'Loi'),('P53',N'Thieu'),('P53',N'HLong’)

select * from @P5


Technique 3 Using For XML Path to concatenate records into
one
c) Combine For XML Path(‘’) & Stuff

SELECT name FROM @p5 FOR XML PATH('')

<name>Giang</name>
<name>Tai</name>
<name>My</name>
<name>VPhuc</name>
<name>Khoi</name>
<name>Tan</name>
<name>TTrang</name>
……
Technique 3 Using For XML Path to concatenate records into
one
c) Combine For XML Path(‘’) & Stuff

SELECT ‘-’+name FROM @p5 FOR XML PATH('')

--Result
-Giang-Tai-My-VPhuc-Khoi-Tan-TTrang-Dien-TPhuong-MPhuong-TPhuc-Hoa-Cuong-
Vien-DTrang-BLong-Manh-Tho-Loi-Thieu-HLong
Technique 3 Using For XML Path to concatenate records into
one
c) Combine For XML Path(‘’) & Stuff

SELECT DISTINCT
Section,
stuff(( SELECT ‘-’+name FROM @p5 a FOR XML PATH('')
)
,1,1,‘’
) as crew
FROM @P5
Technique 3 Using For XML Path to concatenate records into
one
c) Combine For XML Path(‘’) & Stuff

SELECT DISTINCT
Section,
stuff(( SELECT ‘-’+name FROM @p5 a where a.section=b.section
FOR XML PATH('')
,1,1,‘’
)
FROM @P5 as b

--Result
Section Crew
P51 Giang-Tai-My-VPhuc-Khoi-Tan-TTrang-Dien-TPhuong
P52 MPhuong-TPhuc-Hoa-Cuong-Vien-DTrang
P53 BLong-Manh-Tho-Loi-Thieu-HLong
Technique 3 Using For XML Path to concatenate records into
one
Example
Given table: DB.tbpocore01routingdetail, write a SQL syntax to get the MSC-route for
coils:
('201801DA84PN001','201801DA84JA004','201801DA87MN001')

No. MSC No. Order No. Item No. MSC Route


1 800377001 201801DA84JA 004 PL---TCM---CGL---PKL
2 200189001 201801DA84PN 001 PL---PKL
3 500019001 201801DA87MN 001 PL---TCM---ACL---PKL
Technique 3 Using For XML Path to concatenate records into
one
Answer
select a.mscno,a.orderno, a.itemno,
stuff(
(
select '---'+case
when b.millcode='p' then 'PL'
when b.millcode='t' then 'TCM'
when b.millcode='c' then 'CAL'
when b.millcode='g' then 'CGL'
when b.millcode='a' then 'ACL'
when b.millcode='k' then 'PKL'
when b.millcode='l' then 'RCL'
when b.millcode='n' then 'INL'
else b.millcode end
from db.tbpocore01routingdetail b where a.mscno=b.mscno and a.orderno=b.orderno
and a.itemno=b.itemno order by b.mscno, b.seqno asc
for xml path ('')
),1,3,'') as msc_route
from db.tbpocore01routingdetail a
where a.orderno+a.itemno in ('201801DA84PN001','201801DA84JA004','201801DA87MN001')
group by a.mscno, a.orderno, a.itemno
Technique 3 Using For XML Path to concatenate records into
one
Practice
Given table: DB.tbtmbm012, write a SQL syntax to get data as below:

Prod
Lib ID Index ID Description Status Applicable Steel Grade
Detail
CR Commercial Grade FOR AUTOMOBILE
BM FC18 F (270C, SPCC- CQS) from NSSMC narrow N JSC270C- - - SPC270C- - - SPCC- CQS
range
CSVC S- 1008- 3 (FOR CR) (Mod) based on
BM FC38 F N CS TYPE B- - - ASCR CQ1
CR- CQ1
CG Drawing Grade (SGCD1- DQ1, JAC270D) SGCD1- - - JAC270D- - - SCGA270D- - -
BM JD04 J N
from NSSMC, Raw Material : t> = 2.600mm MJAC270D
50CSV600- - - 50CSV700- - - 50CSV800- - -
ES Medium Grade (65CSV1300, 1000, 800,
BM MM01 M N 65CSV1000- - - 65CSV1300- - - 65CSV800- - -
50CSV800, 700, 600) from CSC
65CSV600
Technique 4 Using pivot table in SQL (Crosstab-Query)

The SQL Server PIVOT clause allows you to write a cross tabulation. This means
that you can aggregate your results and rotate rows into columns.
Table A Pivot function
Primary Value
Primary Value SELECT * Coil A Aggregate(a,b,c)
Coil A a FROM
(Select [Primary field], [Value] from [Table A]) Coil B Aggregate(d,e)
Coil A b
Coil C Aggregate(f,g)
Coil A c PIVOT
Coil B d ( <Aggregate function> (<column Value>)
Coil B e FOR [Primary field]
in ([Coil A], [Coil B], [Coil C])
Coil C f ) as PVT
Coil C g

※Aggregate function: SUM(), COUNT(), MIN(), MAX, AVG()…


Technique 4 Using pivot table in SQL (Crosstab-Query)
Basic syntax

SELECT <non-pivoted column>,


[first pivoted column] AS <column name>,
[second pivoted column] AS <column name>,
...
[last pivoted column] AS <column name>
FROM (<SELECT query that produces the data>) AS <alias for the source query>

PIVOT
(
<aggregation function>(<column being aggregated>)
FOR
[<column that contains the values that will become column headers>]
IN ( [first pivoted column], [second pivoted column], ... [last pivoted column])
) AS <alias for the pivot table>
Technique 4 Using pivot table in SQL (Crosstab-Query)
Example
From table @P5fund, create a pivot table as below:

Table @P5fund After using Pivot


Name Month Contribution
Name 8 9 10 11 12
Mr. A 8 50,000
Mr. A 9 90,000 Mr. A 50,000 90,000 100,000 120,000 130,000
Mr. A 10 100,000
Mr. B - - 100,000 150,000 200,000
Mr. A 11 120,000
Mr. A 12 130,000 Mr. C - - 100,000 200,000 300,000
Mr. B 10 100,000
Mr. B 11 150,000
Mr. B 12 200,000
Ms. C 10 100,000
Ms. C 11 200,000
Ms. C 12 300,000
Technique 4 Using pivot table in SQL (Crosstab-Query)
Answer

---Step 1-Create table @P5fund

Declare @P5fund as table


(
Name varchar(10),
Month varchar(15),
Contribution numeric(10)
)
INSERT INTO @P5fund values
('Mr. A','08','50000'),('Mr. A','09','90000'),('Mr. A','10','100000’),
('Mr. A','11','120000'),('Mr. A','12','130000'),
('Mr. B','10','100000'),('Mr. B','11','150000'),('Mr. B','12','200000'),
('Mr. C','10','100000'),('Mr. C','11','200000'),('Mr. C','12','300000’)
Technique 4 Using pivot table in SQL (Crosstab-Query)
Answer
---Step 2- PIVOT
Select name,
isnull([08],0) [08], ---Return NULL value to Zero
isnull([09],0) [09],
isnull([10],0) [10],
isnull([11],0) [11],
isnull([12],0) [12]

from
(select Name, Month, Contribution from @P5fund ) as a

PIVOT
(
sum(contribution)

For Month in ([08],[09],[10],[11],[12])


) as pvt
Technique 4 Using pivot table in SQL (Crosstab-Query)
Answer
---Step 2- PIVOT
Non-pivoted column
Select name,
isnull([08],0) [08], pivoted columns
isnull([09],0) [09],
isnull([10],0) [10],
isnull([11],0) [11],
isnull([12],0) [12] SELECT Clause to produce Query data

from Using Alias


(select Name, Month, Contribution from @P5fund ) as a

PIVOT
( Aggregate function
sum(contribution)
pivoted columns
For Month in ([08],[09],[10],[11],[12])
) as pvt Using Alias
Technique 4 Using pivot table in SQL (Crosstab-Query)
Practice
From given table DB.TBIHAMA01BUY, Write a SQL syntax that summarizes FHS material received in period: 201801 –
201805 following each HR spec.

HR S pe c 201 801 201 802 201 803 201 804 201 805
1006 881,640 20,360 824,015 795,900 266,735
1006 MOD. 838,505 272,760 59,270
1008 23,075 154,605
ASTM A1011 CS TYP E B 1,985,505
ASTM A1011 SS Gr. 33 378,740
ASTM A1011 SS Gr. 36 TYP E 2 67,100
ASTM A1018 CS TYP E B 199,865
CSVC HR- ES- 1 353,990 521,040
F1004- 1(For CR- CQS) 401,940 770,295 272,430
F1006- 1(For CR- CQ1) 1,876,175 107,065 2,179,305 5,333,330 436,910
JIS G 3131:2010 SP HC
SAE 1008 635,820
SP HC 21,525
SP HT1 23,300
SS400 21,180
Thank you!

You might also like