用于列的SQL分组

时间:2016-05-31 14:11:31

标签: sql

我有一个按DeliveryName订购的查询

SELECT ID, CreatedAt, Identifier, Name, DeliveryName, RoundedPriceSum
FROM StarOrder
WHERE  
   SiteID = 1 AND --StarSite.ID 1= SE, 2 = NO
   ShippingTypeID = 4 -- StarShippingType.ID 4 = STORE_PICKUP SE, 10 = STORE_PICKUP NO
   and CreatedAt between '2015/01/11' and '2016/05/30'
Order BY DeliveryName DESC

我正在尝试分组,以便每个交付名称都有总行数,但没有运气。任何帮助都会很棒。

2 个答案:

答案 0 :(得分:2)

您正在选择所有列,包括ID(具有最低粒度或详细数据),那么您如何获得分组数据。你也没有使用group by子句。 您需要选择分组列和摘要数据,例如sum()或avg()count()等来实现此目的。

SELECT DeliveryName, count(*)
FROM StarOrder
WHERE  SiteID = 1 
AND ShippingTypeID = 4 
and CreatedAt between '2015/01/11' and '2016/05/30'
group by DeliveryName 
Order BY DeliveryName DESC

例如,如果您想按班级对学生进行分组,您将选择班级学生人数。但是,如果您选择班级学生姓名,那么您将获得每位学生的排名。

答案 1 :(得分:0)

您可以通过这种方式获取按DeliveryNAme分组的行数

SELECT DeliveryName, count(*)
FROM StarOrder
WHERE  SiteID = 1 
AND ShippingTypeID = 4 
and CreatedAt between '2015/01/11' and '2016/05/30'
group by DeliveryName    
Order BY DeliveryName DESC