在SQL中的GROUP BY获取每月数据细分

时间:2014-06-13 16:58:45

标签: mysql sql logparser

假设我有一个数据描述了销售的不同商品和销售时间。我想细分这些数据并计算每月销售的不同商品。所以这就是我到目前为止所做的:

SELECT 
 ItemDescription
,OrderReceivedData 
,COUNT(*) AS ItemCount 
INTO 'C:\Users\whatever.csv' 
FROM 'C:\user\inputFileHere.csv' 
GROUP BY ItemDescription, OrderReceivedDate 
HAVING OrderReceivedDate LIKE '%2011%'

现在问题是我的日期格式不好。那么上面的查询就是它显示了01JAN2011,02JAN2011,...,10FEB2011等项目的计数。依此类推。但我想要的是JAN2011,FEB2011,MAR2011的数量......等等。所以基本上我不想要GROUP BY OrderReceivedData但我想在OrderReceivedDate中按这些特定的7个字符进行分组,这样我就可以忽略日期。我希望这是有道理的。那我该怎么做?

3 个答案:

答案 0 :(得分:0)

简单的方法,虽然有点黑客,但是你需要解析日期字符,然后分组。为简单起见,您可以按编号引用列。如果您认为这会改变,请重复GROUP BY子句中的解析逻辑。这假定该字段包含两个前导字符:

SELECT 
 ItemDescription
,RIGHT(OrderReceivedData, LEN(OrderReceivedData) - 2) AS MonthOrderReceivedData
,COUNT(*) AS ItemCount 
INTO 'C:\Users\whatever.csv' 
FROM 'C:\user\inputFileHere.csv' 
GROUP BY ItemDescription, 2
HAVING OrderReceivedDate LIKE '%2011%'

我没有测试这段代码,但应该让你走上正轨。

答案 1 :(得分:0)

首先需要使用Log Parser将OrderReceivedDate作为时间戳取消,然后将其格式化为年 - 月并按其分组:

SELECT
   ItemDescription,
   Month,
   COUNT(*) AS TOTAL
USING
   TO_STRING(TO_TIMESTAMP(OrderReceivedDate,'ddMMMyyyy'), 'yyyy-MM') as Month
INTO 
   'C:\Users\whatever.csv' 
FROM 
   'C:\user\inputFileHere.csv' 
WHERE
   OrderReceivedDate LIKE '%2011%'
GROUP BY 
   ItemDescription,
   Month

答案 2 :(得分:-1)

SELECT 
 ItemDescription
,SUBSTR(OrderReceivedDate,2,7) AS OrderReceivedDateUpdated 
,COUNT(*) AS ItemCount 
INTO 'C:\Users\whatever.csv' 
FROM 'C:\user\inputFileHere.csv' 
GROUP BY ItemDescription, OrderReceivedDateUpdated 
HAVING OrderReceivedDate LIKE '%2011%'