简体   繁体   中英

How write sql query group by?

I have a ERD. But I want to write a sql query. The meaning is that you can select all columns of artgrp of regroupid 11 grouped by artdept.

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?

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. 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;
Output will look like this
Blue 3
Grey 17
Red 5

Note: whatever column you use in group by will be used in select columns as well. 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

Ford Blue 3
Ford Grey 7
Honda Red 5
Honda Grey 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().

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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