0

我有以下查询:

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 字母顺序排序?

谢谢你

4

1 回答 1

0

这是一个可能的答案。请注意,在此答案中,该表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。如您所见,使用您在问题中给出的示例,它会产生预期的结果。

于 2013-08-08T18:51:05.530 回答