知道我该怎么做吗?
我想要GROUP BY Fault和Stream and Part但是在这些分组中我想按频率排序?
请帮忙。
米克
select
p.part_no as Part,
p.product_description as Description,
p.brand_id as Brand,
p.part_product_family as Stream,
p.range as Range_Name,
fa.description as Area,
f.description as Fault,
count(f.description) as Frequency
from recorded_faults rf, faults f, fault_areas fa, losses l, products p
WHERE rf.fault_id = f.id
and f.fault_area_id = fa.id
and rf.loss_id = l.id
and p.id = l.product_id
group by
Fault,
Stream,
Part
order by Frequency desc
答案 0 :(得分:0)
你可以试试这个:
select
p.part_no as Part,
p.product_description as Description,
p.brand_id as Brand,
p.part_product_family as Stream,
p.range as Range_Name,
fa.description as Area,
f.description as Fault,
count(f.description) as Frequency
from recorded_faults rf inner join faults f on rf.fault_id = f.id
inner join fault_areas fa on f.fault_area_id = fa.id
inner join losses l on rf.loss_id = l.id
inner join products p on p.id = l.product_id
group by
p.part_no,
p.product_description,
p.brand_id,
p.part_product_family,
p.range,
fa.description,
f.description,
order by count(f.description) desc
尽量避免使用逗号分隔的JOINS,不再推荐使用它们
您还需要将select
的列放在GROUP BY
答案 1 :(得分:0)
如果要将为子组返回的行保持在一起,则必须按用于分组的相同条件(前缀)对行进行排序,然后添加所需的任何额外表达式。
例如,如果您希望同时获取Fault
的值相同的行并按Frequency
排序,而不关心Stream
,那么您可以写下:
GROUP BY Fault, Stream, Part
ORDER BY Fault, Frequency DESC
如果您还希望将具有相同值Fault
和Stream
的行保持在一起,那么您还要将Stream
添加到ORDER BY
子句中:
GROUP BY Fault, Stream, Part
ORDER BY Fault, Stream, Frequency DESC
对ORDER BY Fault, Stream, Part, ...
没有任何意义,因为GROUP BY
为Fault
,Stream
和Part
的每个组合生成一行。
作为旁注,SQL允许您按其他标准对行进行排序。例如,GROUP BY Fault, Stream, Part ORDER BY Part, Fault, Frequency DESC
完全有效并产生正确的结果,但对于您的应用程序实现的业务而言,它很可能毫无意义。