假设我有3个表(如下所示)。
series_no 表:
| id | desc_seriesno |
|:------|----------------:|
| 7040 | AU1011 |
| 7041 | AU1022 |
| 7042 | AU1033 |
| 7043 | AU1044 |
| 7044 | AU1055 |
| 7045 | AU1066 |
品牌表:
| id | desc_brand |
|:------|----------------:|
| 1020 | Audi |
| 1021 | Bentley |
| 1022 | Ford |
| 1023 | BMW |
| 1024 | Mazda |
| 1025 | Toyota |
car_info 表格:
| seriesno_id | brand_id | color |
|:---------------|------------|--------:|
| 7040 | 1020 | white |
| 7040 | 1020 | black |
| 7040 | 1020 | pink |
| 7041 | 1021 | yellow |
| 7041 | 1021 | brown |
| 7042 | 1022 | purple |
| 7042 | 1022 | black |
| 7042 | 1022 | green |
| 7043 | 1023 | blue |
| 7044 | 1024 | red |
| 7045 | 1025 | maroon |
| 7045 | 1025 | white |
如何分组或组合相似/相同的字符串而不在连接字符串中更改它们,而只是覆盖相同的字符串。
这是我对sql server 2014的当前查询: -
SELECT SN.id AS seriesid, B.id AS brandid, B.desc_brand
FROM [db1].[dbo].[series_no] SN
LEFT JOIN [db1].[dbo].[car_info] CI
ON CI.seriesno_id = SN.id
RIGHT JOIN [db1].[dbo].[brand] B
ON B.id = CI.brand_id
GROUP BY SN.id, B.id, B.desc_brand
ORDER BY SN.id ASC
但遗憾的是它给了我一个错误,因为我不能用这样的字符串分组。
我希望它是这样的: -
| seriesid | brandid | desc_brand |
|:-----------|------------|--------------:|
| 7040 | 1020 | Audi |
| 7041 | 1021 | Bentley |
| 7042 | 1022 | Ford |
| 7043 | 1023 | BMW |
| 7044 | 1024 | Mazda |
| 7045 | 1025 | Toyota |
而不是这个(连接字符串): -
| seriesid | brandid | desc_brand |
|:-----------|------------|----------------------:|
| 7040 | 1020 | Audi, Audi, Audi |
| 7041 | 1021 | Bentley, Bentley |
| 7042 | 1022 | Ford, Ford, Ford |
| 7043 | 1023 | BMW |
| 7044 | 1024 | Mazda |
| 7045 | 1025 | Toyota, Toyota |
答案 0 :(得分:0)
您只需要 避免重复 ,因此请使用以下两种方法之一:
分组
select col1, col2 ..
from table1 a inner join table2 b
on ..
group by col1, col2 ..
鲜明
select distinct col1, col2 ..
from table1 a inner join table2 b
on ..
<强>演示: - 强>
Create database TestDB
go
use TestDB
go
Create table series_no (id int ,desc_seriesno varchar(20) )
go
insert into series_no values (7040, 'AU1011'),
(7041, 'AU1022'),
(7042, 'AU1033'),
(7043, 'AU1044'),
(7044, 'AU1055'),
(7045, 'AU1066')
go
Create table brand (id int ,desc_brand varchar(20) )
go
insert into brand values (1020, 'Audi'),
(1021, 'Bentley'),
(1022, 'Ford'),
(1023, 'BMW'),
(1024, 'Mazda'),
(1025, 'Toyota')
Create table car_info (seriesno_id int ,brand_id varchar(20), color varchar (20) )
go
insert into car_info values(7040,1020,'white'),
(7040,1020,'black'),
(7040,1020,'pink'),
(7041,1021,'yellow'),
(7041,1021,'brown'),
(7042,1022,'purple'),
(7042,1022,'black'),
(7042,1022,'green'),
(7043,1023,'blue'),
(7044,1024,'red'),
(7045,1025,'maroon'),
(7045,1025,'white')
go
select a.seriesno_id as seriesnoid, a.brand_id as brandid,b.desc_brand
from car_info a inner join brand b
on brand_id = id
group by a.seriesno_id , a.brand_id ,b.desc_brand
/*
-- Or
select distinct a.seriesno_id as seriesnoid, a.brand_id as brandid,b.desc_brand
from car_info a inner join brand b
on brand_id = id
*/
<强>结果: - 强>