我有以下查询:
SELECT *
FROM vendors_parts INNER JOIN
vendors ON vendors_parts.vendor = vendors.vendor_id
WHERE (vendors_parts.vendor = @vendor_id) AND (vendors_parts.active = @active) OR
(vendors_parts.vendor = @vendor_id) AND (vendors_parts.active = @inactive)
ORDER BY vendors_parts.old_id, vendors_parts.vendor_part, date_start DESC, vendors_parts.active DESC
它以以下格式返回数据:
vendor_part active old_id
b 1 1
a 0 1
a 0 1
b 0 1
x 1 3
z 1 5
c 1 20
c 0 20
我的问题是,如何在对vendor_part进行升序和活动降序排序时将old_id保持在一起?我想要的输出是:
vendor_part active old_id
b 1 1
a 0 1
a 0 1
b 0 1
c 1 20
c 0 20
x 1 3
z 1 5
我还尝试了对old_id进行分组的子查询,但这将我限制为仅一个唯一的old_id:
SELECT *
FROM
(
SELECT * FROM vendors_parts INNER JOIN vendors ON vendors_parts.vendor = vendors.vendor_id
WHERE (vendors_parts.vendor = @vendor_id) AND (vendors_parts.active = @active) OR (vendors_parts.vendor = @vendor_id) AND (vendors_parts.active = @inactive)
GROUP BY vendors_parts.old_id
) temp_table
ORDER BY vendor_part
如何显示所有old_id分组在一起,并按其各自组中的vendor_part按字母顺序排序?
谢谢
最佳答案
这是一个可能的答案。请注意,在此答案中,表tbl
是实际(相当复杂)查询的占位符(我不喜欢这样做,但是您可能必须使用临时表来使查询语法易于管理):
SELECT tbl.* FROM tbl
JOIN (SELECT MIN(vendor_part) as mvp, old_id FROM tbl GROUP BY old_id) as driver
USING (old_id)
ORDER BY driver.mvp, tbl.old_id, active DESC, tbl.vendor_part
有关实时演示,请参见http://sqlfiddle.com/#!2/c53a9/4。如您所见,使用您在问题中给出的示例,它可以产生预期的结果。