Question

I have a table of data with a timestamp field.

For the analysis that I am working on I need to create a table that is 7 fields wide and 24 records down: 7 days of the week and 24 hours of the day.

The goal is to look at a particular event by hour of week.

With my current level of knowledge in SQL I was going to attempt something like:

SELECT EXTRACT(DAY FROM THE_TIMESTAMP_FIELD) = 1, EXTRACT(DAY FROM THE_TIMESTAMP_FIELD) = 2, etc

But:

  1. I'm using Teradata and datepart() or datename() do not seem to work (For the day name e.g. Mon, Tue, wed etc)
  2. The SELECT statement example above will produce day of the month (1st, 2nd, 3rd etc).

Is there a better way to SELECT each day of the week, rather than manually typing a EXTRACT statement for each day 1:7?

How would I even extract the dayname in teradata?

Was it helpful?

Solution

You want a kind of PIVOT query, which is unfortunately not supported in TD.

But it's possible, looks like a lot of source code, but it's mainly cut & paste & modify.

Assuming a table tab with a timestamp column tsand you want to average column col:

SELECT
   EXTRACT(HOUR FROM ts) as "hour"
  ,AVG(CASE WHEN ts (FORMAT 'eee') (CHAR(3)) = 'mon' THEN col END) AS mon
  ,AVG(CASE WHEN ts (FORMAT 'eee') (CHAR(3)) = 'tue' THEN col END) AS tue
  ,AVG(CASE WHEN ts (FORMAT 'eee') (CHAR(3)) = 'wed' THEN col END) AS wed
  ,AVG(CASE WHEN ts (FORMAT 'eee') (CHAR(3)) = 'thu' THEN col END) AS thu
  ,AVG(CASE WHEN ts (FORMAT 'eee') (CHAR(3)) = 'fri' THEN col END) AS fri
  ,AVG(CASE WHEN ts (FORMAT 'eee') (CHAR(3)) = 'sat' THEN col END) AS sat
  ,AVG(CASE WHEN ts (FORMAT 'eee') (CHAR(3)) = 'sun' THEN col END) AS sun
FROM tab
GROUP BY 1
ORDER BY 1

Btw, EXTRACT(DAY...) doesn't return the day of week, it's the day of month, i.e. 1..31

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top