SQL for Data science : SQL for XML Path เพื่อ concat ข้อมูลหรือ Grouping ข้อมูล
จากรูปด้านล่างกรณีที่เราต้องการ Grouping ข้อมูลในแต่ละเดือน (order date คือ end of month) และนำ Product มา concat ต่อๆกันไป จากนั้นทำการ Sum ยอดทั้งหมดในเดือนนั้นๆ
จะสามารถเขียน SQL ได้ยังไง
ตัวอย่าง SQL Script
–Prepare Data Demo
with [data_demo] as (
select order_date=’2017-01-31′,product=’Notebook’ , price = 32000
union all
select order_date=’2017-01-31′,product=’Mouse’ , price = 750
union all
select order_date=’2017-02-28′,product=’Notebook’ , price = 32000
union all
select order_date=’2017-02-28′,product=’Monitor’ , price = 18000
union all
select order_date=’2017-02-28′,product=’Keyboard’ , price = 450
)
–Script Select
select order_date
,product = (select quotename(product) from [data_demo]
where a.order_date = order_date for xml path(”),type).value(‘.’,’varchar(max)’)
,sum(price) as price
from [data_demo] a
group by order_date
ทดลองรัน script ผ่าน SQL Server Management studio