选择最长独特字符串的行
我试图弄清楚如何从表中选择一个行的子集,每个“父”字符串最长的唯一字符串。我将在下面提供表示例,而我的代码无效。
Current Table:
Name | SalePrice |
---|---|
NorthAmerica\US\Northeast\NewYork | 8576 |
NorthAmerica\US\Northeast | 2598 |
SouthAmerica\Brazil | 1348 |
SouthAmerica\Chile\NorthEast | 9726 |
SouthAmerica\Chile | 4412 |
NorthAmerica\Canada\Ontario | 3894 |
NorthAmerica\Canada | 6321 |
Desired Output:
Name | SalePrice |
---|---|
NorthAmerica\美国\东北\ Newyork | 8576 |
Southamerica \巴西 | 1348 |
Southamerica \ Chile \ Northeast | 9726 |
Northamerica \ Canada \ Canada \ Ontario | 3894 |
最初,我认为我可以基于Backslashes()(
example: SELECT * FROM TestTable WHERE Name LIKE '%\\%'
)( )()()。但是,此逻辑不起作用,因为某些最远的分支可能只有1个后斜线,而其他分支可能有3个以上。
生成测试表的代码如下,任何帮助/建议都将不胜感激
create table t1(
[name] varchar(60),
[saleprice] int );
insert into t1 values ('NorthAmerica\US\Northeast\NewYork',8576);
insert into t1 values ('NorthAmerica\US\Northeast',2598);
insert into t1 values ('SouthAmerica\Brazil',1348);
insert into t1 values ('SouthAmerica\Chile\NorthEast',9726);
insert into t1 values ('SouthAmerica\Chile',4412);
insert into t1 values ('NorthAmerica\Canada\Ontario',3894);
insert into t1 values ('NorthAmerica\Canada',6321);
I'm trying to figure out how to select a subset of rows from a table, with the longest unique string for each "parent" string. I'll provide table examples below and my code that didn't work.
Current Table:
Name | SalePrice |
---|---|
NorthAmerica\US\Northeast\NewYork | 8576 |
NorthAmerica\US\Northeast | 2598 |
SouthAmerica\Brazil | 1348 |
SouthAmerica\Chile\NorthEast | 9726 |
SouthAmerica\Chile | 4412 |
NorthAmerica\Canada\Ontario | 3894 |
NorthAmerica\Canada | 6321 |
Desired Output:
Name | SalePrice |
---|---|
NorthAmerica\US\Northeast\NewYork | 8576 |
SouthAmerica\Brazil | 1348 |
SouthAmerica\Chile\NorthEast | 9726 |
NorthAmerica\Canada\Ontario | 3894 |
Originally, I thought I could apply some form of logic based off the number of backslashes (
example: SELECT * FROM TestTable WHERE Name LIKE '%\\%'
). However, this logic doesn't work because some names furthest branch may only have 1 backslash while others may have 3+.
Code to generate test table is below and any help/advice would be greatly appreciated
create table t1(
[name] varchar(60),
[saleprice] int );
insert into t1 values ('NorthAmerica\US\Northeast\NewYork',8576);
insert into t1 values ('NorthAmerica\US\Northeast',2598);
insert into t1 values ('SouthAmerica\Brazil',1348);
insert into t1 values ('SouthAmerica\Chile\NorthEast',9726);
insert into t1 values ('SouthAmerica\Chile',4412);
insert into t1 values ('NorthAmerica\Canada\Ontario',3894);
insert into t1 values ('NorthAmerica\Canada',6321);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用操作员
喜欢
与不出现
:请参阅演示。
Use the operator
LIKE
withNOT EXISTS
:See the demo.