Advanced SQL (Draft)
Advanced SQL (Draft)
Exclusively for P5
Jun-2018
Agenda
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
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> ]
) 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’
GROUP BY A.PRODUCTCOILNO
) AS A1
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
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
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
XML Path
For
Stuff
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
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(‘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’)
<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
--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')
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
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:
from
(select Name, Month, Contribution from @P5fund ) as a
PIVOT
(
sum(contribution)
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!