mySQL命令和分组依据

时间:2016-05-11 11:38:18

标签: mysql sql

知道我该怎么做吗?

我想要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

2 个答案:

答案 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

如果您还希望将具有相同值FaultStream的行保持在一起,那么您还要将Stream添加到ORDER BY子句中:

GROUP BY Fault, Stream, Part
ORDER BY Fault, Stream, Frequency DESC

ORDER BY Fault, Stream, Part, ...没有任何意义,因为GROUP BYFaultStreamPart的每个组合生成一行。

作为旁注,SQL允许您按其他标准对行进行排序。例如,GROUP BY Fault, Stream, Part ORDER BY Part, Fault, Frequency DESC完全有效并产生正确的结果,但对于您的应用程序实现的业务而言,它很可能毫无意义。