简体   繁体   English

如何编写sql查询组?

[英]How write sql query group by?

I have a ERD.我有一个 ERD。 But I want to write a sql query.但是我想写一个sql查询。 The meaning is that you can select all columns of artgrp of regroupid 11 grouped by artdept.意思是可以选择按artdept分组的regroupid 11的artgrp的所有列。

I have this:我有这个:

Select *
From artgrp
Where regroudid = "11"
Group by artdept;

My question is: how can I write: select all columns of artgrp group by the columns of artdept?我的问题是:我该怎么写:通过artdept的列选择artgrp组的所有列?

Here is my model这是我的模型

在此处输入图片说明

Group by is used to identify the count, max, min, avg, etc in a cluster of data.分组依据用于识别数据集群中的计数、最大值、最小值、平均值等。 To be more clear say for instance you have Cars table with fields make, color, price.更清楚地说,例如您有包含制造、颜色、价格字段的 Cars 表。 And you want to see the count of cars in different colors(this will be cluster of different colors) you can use the following query并且您想查看不同颜色的汽车数量(这将是不同颜色的集群),您可以使用以下查询

select count(1),color from cars group by color;按颜色从汽车组中选择计数(1),颜色;
Output will look like this输出将如下所示
Blue 3蓝3
Grey 17灰色 17
Red 5红5

Note: whatever column you use in group by will be used in select columns as well.注意:您在 group by 中使用的任何列也将在选择列中使用。 In the above example I grouped by using color if add more fields say for instance make it will have two clusters(color,make) output would be在上面的例子中,如果添加更多字段,我使用颜色分组,例如 make 它将有两个 cluster(color,make) 输出将是

Ford Blue 3福特蓝 3
Ford Grey 7福特灰色 7
Honda Red 5本田红5
Honda Grey 10本田灰色 10

So you can identify what is the function you need to perform before grouping your data like count, min, max, avg, rank etc. And if you want all the fields in your select clause you will have to use analytical function.因此,您可以在对数据(如计数、最小值、最大值、平均值、排名等)进行分组之前确定需要执行的函数。如果您想要选择子句中的所有字段,则必须使用分析函数。 Edit your question with sample data also with expected output, I can give you the answer with analytical query as well if required.使用示例数据和预期输出编辑您的问题,如果需要,我也可以通过分析查询为您提供答案。

Thanks for editing your question sample data will be more clear, still I will go ahead with what I understood.感谢您编辑您的问题示例数据会更清楚,但我仍然会继续我的理解。 I am using analytical function here as solution我在这里使用分析函数作为解决方案

Select artgrpid,description,descid,relgroupid,
artdeptid,default,name,brand,questions,
ROW_NUMBER() over (Prtition by artdeptid order by artdeptid) from 
artgrp;

you can use rank() or count(1) etc instead of ROW_NUMBER().您可以使用 rank() 或 count(1) 等代替 ROW_NUMBER()。

SELECT d.description, d.lifetime, d.name, COUNT(d.artdeptid) as Departments
FROM artgrp g INNER JOIN arddept d ON g.artdeptid = d.artdeptid
WHERE regroudid = "11"
GROUP BY d.description, d.lifetime, d.name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM