Planning to use a table for storing all trip points for every trips, how to get required output based on below table data using SQL Server T-SQL statement or I need to re-define the table structure?
Raw data in [trip-points]
table:
| Trip Type | Trip Name | Trip Loc seq | Trip Point No | Trip Point Name |
| ------------ | ------------ | ------------ | ------------ | ------------ |
| TRAVEL | N-ASIA | 1 | 0001 | HK |
| TRAVEL | N-ASIA | 2 | 0002 | Japan |
| TRAVEL | N-ASIA | 3 | 0003 | South Korea |
| TRAVEL | S-ASIA | 1 | 0004 | Thailand |
| TRAVEL | S-ASIA | 2 | 0005 | Singapore |
| BUSINESS | N-ASIA | 1 | 0001 | HK |
| BUSINESS | N-ASIA | 2 | 0006 | TAIWAN |
Expected result:
Trip Type | Trip Name | Trip Point 01 | Trip Point 02 | Trip Point 03 |
---|---|---|---|---|
TRAVEL | N-ASIA | 0001-HK | 0002-Japan | 0003-South Korea |
TRAVEL | S-ASIA | 0004-Thailand | 0005-Singapore | |
BUSINESS | N-ASIA | 0001-HK | 0006-TAIWAN |
3条答案
按热度按时间ffvjumwh1#
We can use a pivot query approach here. Assuming there would only be a maxmimum of 3 trip points:
5cg8jx4n2#
data
use
pivot
andconcat
as followsdbfiddle
3pmvbmvn3#
You need to prepare a dynamic query based on the MAX of Trip_Loc_seq.
Data Preperation:
Dynamic SQL Query: