我有一個這樣的示例表,我想使用 SQL 查詢根據 orderID 列按字母順序將列中的區域、國家、城市值的條目列排序為行。
| 串列 | 訂單號 | 入口 |
|---|---|---|
| 串列1 | AA | 亞洲 |
| 串列1 | AAA | 日本 |
| 串列1 | AAB | 泰國 |
| 串列1 | AB | 歐洲 |
| 串列1 | ABA | 德國 |
| 串列1 | ABAA | 柏林 |
| 串列1 | ABAB | 慕尼黑 |
| 串列1 | ABAC | 漢堡 |
預期輸出:
| 串列 | 地區 | 國家 | 城市 |
|---|---|---|---|
| 串列1 | 亞洲 | 日本 | |
| 串列1 | 亞洲 | 泰國 | |
| 串列1 | 歐洲 | 德國 | 柏林 |
| 串列1 | 歐洲 | 德國 | 慕尼黑 |
| 串列1 | 歐洲 | 德國 | 漢堡 |
uj5u.com熱心網友回復:
我們使用內連接將國家連接到大陸,使用另一個內連接將城市連接到國家。
select list, region, country, city
from (
select t.list
,t2.entry as region
,t3.entry as country
,case when t.entry != t3.entry then t.entry end as city
,case when count(*) over(partition by t3.entry) > 1 and t3.entry = t.entry then 1 end as mrk
,t.orderID
from t join t t2 on t2.orderID in(left(t.orderID, 2)) and t.entry != t2.entry join t t3 on t3.orderID in(left(t.orderID, 3))
) t
where mrk is null
order by t.orderID
| 串列 | 地區 | 國家 | 城市 |
|---|---|---|---|
| 串列1 | 亞洲 | 日本 | 無效的 |
| 串列1 | 亞洲 | 泰國 | 無效的 |
| 串列1 | 歐洲 | 德國 | 柏林 |
| 串列1 | 歐洲 | 德國 | 慕尼黑 |
| 串列1 | 歐洲 | 德國 | 漢堡 |
小提琴
uj5u.com熱心網友回復:
您可以為此使用視窗函式,這很可能會比 3 個連接更好。
declare @MyData table (list varchar(5), orderID varchar(4), [entry] varchar(12));
insert into @MyData (list, orderID, [entry])
values
('list1', 'AA', 'Asia'),
('list1', 'AAA', 'Japan'),
('list1', 'AAB', 'Thailand'),
('list1', 'AB', 'Europe'),
('list1', 'ABA', 'Germany'),
('list1', 'ABAA', 'Berlin'),
('list1', 'ABAB', 'Munich'),
('list1', 'ABAC', 'Hamburg');
with cte as (
select list
-- Determine the region by partitioning of the 1st 2 characters
, max(case len(orderId) when 2 then [entry] else null end) over (partition by substring(orderId, 1, 2)) Region
-- Determine the country by partitioning of the 3rd character
, max(case len(orderId) when 3 then [entry] else null end) over (partition by substring(orderId, 1, 3)) Country
-- Determine the city by checking the 4th character
, case len(orderId) when 4 then [entry] else null end City
-- Determine whether a city exists for the country, if not, show the country with a null city
, max(case len(orderId) when 4 then [entry] else null end) over (partition by substring(orderId, 1, 2)) City1
from @MyData
)
select list, Region, Country, City
from cte c1
where City is not null
or (Country is not null and City1 is null);
回報:
| 串列 | 地區 | 國家 | 城市 |
|---|---|---|---|
| 串列1 | 亞洲 | 日本 | 無效的 |
| 串列1 | 亞洲 | 泰國 | 無效的 |
| 串列1 | 歐洲 | 德國 | 柏林 |
| 串列1 | 歐洲 | 德國 | 慕尼黑 |
| 串列1 | 歐洲 | 德國 | 漢堡 |
請注意,正如我所展示的那樣,提供 DDL DML 幾乎肯定會確保您更快地獲得答案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/512144.html
上一篇:使用pySpark讀取未存盤在HDFS上的ORC檔案
下一篇:獲取選定節點之后的節點
