我正在处理一组车辆数据,它们都在同一张表中,并使用以下查询:
SELECT
a.VIN_NUM AS [Registration VIN]
,DISTINCT STUFF(SUBSTRING(a.VIN_NUM, 1, 10),9,1,'_') AS [VIN STRING]
FROM
dbo.DMV_All_Tests AS a
WHERE
KeyDateTime between '2017/12/01' and '2018/11/30' AND
INSP_TEST_TYPE = 'B' AND
INSP_ATTEMPT_NUM = '1' AND
EPA_VEHICLE_TYPE = 'HDV'
ORDER BY
[VIN STRING] DESC
该查询从表中提取车辆VIN(VIN_NUM)及其主要代码标识VIN STRING。因此,例如1ABCD23EF4G567890变为1ABCD23_F。 DISTINCT将识别表中为期一年的数据集中的每个唯一VIN STRING组合(约有3万名成员)。
我的目标是举一个VIN NUM的示例,以匹配每个不同的VIN STRING。查询结果的每一行将有两列/成员-VIN STRING(1ABCD23_F),并且该行的下一列将从VIN STRING(1ABCD23EF4G567890)的表中给出一个VIN_NUM示例。
我认为这只是一个选择VIN NUM的第一个实例的SELECT TOP ONE,但我不确定如何构造标准匹配的VIN NUM来伴随每个VIN STRING。它会涉及内部联接吗?
任何建议将不胜感激!
答案 0 :(得分:0)
SELECT
Max(a.VIN_NUM) AS [Registration VIN]
, STUFF(SUBSTRING(a.VIN_NUM, 1, 10),9,1,'_') AS [VIN STRING]
FROM
dbo.DMV_All_Tests AS a
WHERE
KeyDateTime between '2017/12/01' and '2018/11/30' AND
INSP_TEST_TYPE = 'B' AND
INSP_ATTEMPT_NUM = '1' AND
EPA_VEHICLE_TYPE = 'HDV'
GROUP BY
STUFF(SUBSTRING(a.VIN_NUM, 1, 10),9,1,'_')
ORDER BY
[VIN STRING] DESC