GROUP BY

GROUP BY bayonoti bir xil qiymatlarga ega bo'lgan qatorlarni umumiy qatorlarga guruhlaydi, masalan "har bir mamlakatdagi mijozlar sonini topish".

SU

SQL GROUP BY Bayonoti

GROUP BY bayonoti bir xil qiymatlarga ega bo'lgan qatorlarni umumiy qatorlarga guruhlaydi, masalan "har bir mamlakatdagi mijozlar sonini topish".

GROUP BY bayonoti ko'pincha agregat funksiyalar (COUNT(), MAX(), MIN(), SUM(), AVG()) bilan birga ishlatiladi, natija to'plamini bir yoki bir nechta ustunlar bo'yicha guruhlash uchun.

GROUP BY Sintaksisi

SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);

Demo Ma'lumotlar Bazasi

Ushbu o'quv qo'llanmada Northwind namunaviy ma'lumotlar bazasidan "Customers" jadvalidan bir tanlov:

CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
1Alfreds FutterkisteMaria AndersObere Str. 57Berlin12209Germany
2Ana Trujillo Emparedados y heladosAna TrujilloAvda. de la Constitución 2222México D.F.05021Mexico
3Antonio Moreno TaqueríaAntonio MorenoMataderos 2312México D.F.05023Mexico
4Around the HornThomas Hardy120 Hanover Sq.LondonWA1 1DPUK
5Berglunds snabbköpChristina BerglundBerguvsvägen 8LuleåS-958 22Sweden

SQL GROUP BY Misollari

Quyidagi SQL bayonoti har bir mamlakatdagi mijozlar sonini ro'yxatga oladi:

SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;

Quyidagi SQL bayonoti har bir mamlakatdagi mijozlar sonini yuqoridan pastga tartibda ro'yxatga oladi:

SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;

Demo Ma'lumotlar Bazasi

Ushbu o'quv qo'llanmada Northwind namunaviy ma'lumotlar bazasidan "Orders" jadvalidan bir tanlov:

OrderIDCustomerIDEmployeeIDOrderDateShipperID
102489051996-07-043
102498161996-07-051
102503441996-07-082

Va "Shippers" jadvalidan bir tanlov:

ShipperIDShipperName
1Speedy Express
2United Package
3Federal Shipping

GROUP BY JOIN Bilan Misol

Quyidagi SQL bayonoti har bir yetkazib beruvchi tomonidan yuborilgan buyurtmalar sonini ro'yxatga oladi:

SELECT Shippers.ShipperName, COUNT(Orders.OrderID) AS NumberOfOrders
FROM Orders
LEFT JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID
GROUP BY ShipperName;

Ushbu sahifada

Xato haqida xabar berish