如果我有两张桌子:
PartDetailsTable
Id Details Price Brand Id
--------------------------------------------------------
1 {"partNumber":"012345","qty":14} 14.99 1
2 {"partNumber":"012345","qty":11} 4.88 1
3 {"partNumber":"44444","qty":1} 3.24 3
4 {"partNumber":"72431223","qty":9} 3.33 1
5 {"partNumber":"98989","qty":1} 3.33 2
Brands Table
Id BrandName
----------
1 BrandOne
2 BrandTwo
3 BrandThree
我想从 PartDetailsTable 返回Details.PartNumber、Details.Qty 和 BrandId,但还包括 BrandName
我正在使用这个:
SELECT DISTINCT i.id,
JSON_VALUE(i.Details, '$.partNumber') AS 'PartNumber',
i.BrandId,
b.Name AS 'BrandName',
JSON_VALUE(i.Details, '$.qty') AS 'Qty',
FROM
PartDetailsTable i INNER JOIN Brands b ON (i.BrandId = b.Id)
但我想删除重复的零件编号记录,因此对于上面的 PartDetailsTable 中的示例,我只想返回 1,3,4,5 记录,请提供任何建议(因为 id 1 和 2 具有相同的零件编号 012345 (我不需要对数量或类似内容进行求和,只需选择一个并删除任何重复项
您可以按 JSON_VALUE 将其分组,然后获取 MIN(索引),连接回同一张表以获取数量
SELECT i.id,
JSON_VALUE(i.Details, '$.partNumber') AS 'PartNumber',
i.BrandId,
b.Name AS 'BrandName',
JSON_VALUE(i.Details, '$.qty') AS 'Qty',
FROM (
SELECT JSON_VALUE(Details, '$.partNumber') AS 'PartNumber', MIN(Id) [Id]
FROM PartnerDetailsTable
GROUP BY JSON_VALUE(Details, '$.partNumber')
) gi
JOIN PartnerDetailsTable i
ON i.Id = gi.Id
INNER JOIN Brands b
ON i.BrandId = b.Id