Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a timestamp function in a GROUP BY

I'm working with a large transaction data set and would like to group a count of individual customer transactions by month. I am unable to use the timestamp function in the GROUP BY and return the following error:

BAD_QUERY (expression STRFTIME_UTC_USEC([DATESTART], '%b') in GROUP BY is invalid)

Is there a simple workaround to achieve this or should I build a calendar table (which may be the simplest option)?

like image 994
DWGKNZ Avatar asked Sep 04 '12 11:09

DWGKNZ


People also ask

Can we use function in GROUP BY?

The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.

Can we use ORDER BY and GROUP BY at the same time?

Using Group By and Order By Together When combining the Group By and Order By clauses, it is important to bear in mind that, in terms of placement within a SELECT statement: The GROUP BY clause is placed after the WHERE clause. The GROUP BY clause is placed before the ORDER BY clause.

Can we use count with GROUP BY clause?

The count() function with the GROUP BY clause is used to count the data which were grouped on a particular attribute of the table.

Can you GROUP BY date in SQL?

To group by date part, use the GROUP BY clause and the EXTRACT() function. Pass EXTRACT() the date parts to isolate.


2 Answers

@Charles is correct but as an aside you can also group by column number.

SELECT STRFTIME_UTC_USEC(DATESTART, '%b') as month, COUNT(TRANSACTION) as count
FROM [datasetId.tableId]
GROUP BY 1
ORDER BY 2 DESC
like image 179
j.davies Avatar answered Oct 16 '22 21:10

j.davies


You have to use an alias:

SELECT STRFTIME_UTC_USEC(DATESTART, '%b') as month, COUNT(TRANSACTION)
FROM datasetId.tableId
GROUP BY month
like image 33
Charles Avatar answered Oct 16 '22 21:10

Charles