RandomQuestion
RandomQuestion

Reputation: 6998

Dynamically select column - Oracle SQL query

This question might seem completely idiotic but here it goes.

Is it possible to specify/use dynamic column names in sql query.

For e.g. Let’s say Table has following columns.

Column: "1",  "2", "3", "4", "5"

Then for given value of X (coming from DATEDIFF function) let’s say 3 – I want to get sum of values in columns from “1” to “3”. For X = 4, sum of values in columns from “1” to “4” and so on…

Actual Problem:

This table is basically for tracking how many times a particular user logged in past X days. X is defined. We update the record only when user actually logs in. So to be able to calculate correct value at any point of time, I thought of this schema.

"User", "LastLoginDate", "1", "2", "3", "4", "5",

"1" - represents number of times user logged in on 1 day before `LastLoginDate`
"2" - represents number of times user logged in on 2 day before `LastLoginDate`
 and so on..

Now to calculate value on LastLoginDate + 2 days - I just sum values in columns "1", "2", "3". Values in columns "4" and "5" are stale because 2 days have passed.

I hope I was able to explain question correctly.

Jitendra

Upvotes: 1

Views: 908

Answers (1)

mdahlman
mdahlman

Reputation: 9390

I think you'll be a lot happier with a table like this:

create table login_counts (
   user       varchar2(30)
  ,the_date   date
  ,num_logins integer
);

Each time a user logs in you can increment the relevant row. (You can delete old rows at the same time if you want.) Selecting the sum of logins during a specified time period like "today - 2 days" or "last_login - 2 days" is simple with this structure.

Upvotes: 3

Related Questions