1

I have a table of these columns:

userID, date, NumberofLogins

Basically records on which date how many times the user has logged in.

How can I turn this into a table with the following one using SQL query?

UserID, NumberofLoginsDate1, NumberofLoginsDate2, ..., NumberofLoginsDate31.

I only have data for a months, so this should be fine.

fthiella
  • 48,073
  • 15
  • 90
  • 106
user1552372
  • 111
  • 6

2 Answers2

0

Note: assumed for MySQL (hence use of Current_Date function, not available in all DBMS).

SELECT userID
     , Sum(CASE WHEN `date` = Current_Date THEN NumberofLogins END) As NumberofLoginsDate1
     , Sum(CASE WHEN `date` = DateAdd(dd, -1, Current_Date) THEN NumberofLogins END) As NumberofLoginsDate2
     , Sum(CASE WHEN `date` = DateAdd(dd, -2, Current_Date) THEN NumberofLogins END) As NumberofLoginsDate3
     , ...
     , Sum(CASE WHEN `date` = DateAdd(dd, -31, Current_Date) THEN NumberofLogins END) As NumberofLoginsDate31
FROM   your_table
GROUP
    BY userID
gvee
  • 16,732
  • 35
  • 50
  • Worked pretty well. My table is not huge, I don't know if there will be performance issue if the table is huge? – user1552372 Sep 09 '13 at 09:08
  • I'm afraid I am not familiar enough with EXAPlus to comment. However if this were in MySQL or SQL Server I would implement this method over the other option posted (with performance in mind). – gvee Sep 09 '13 at 09:17
0

Could also be done by a pivot query. Repeat the Dx parts till 31. If your table has more data than August add a filter for that too. ( MONTH(date) = 8 )

SELECT 
U.userID
,D1.NumberofLogins AS NumberofLoginsDate1
,D2.NumberofLogins AS NumberofLoginsDate2
,Dx.NumberofLogins AS NumberofLoginsDatex
...

FROM (SELECT DISTINCT userID FROM tblLogins) U
LEFT JOIN (SELECT userID, NumberofLogins FORM tblLogins WHERE DAY(date) = 1) D1
ON U.userID = D1.userID
LEFT JOIN (SELECT userID, NumberofLogins FORM tblLogins WHERE DAY(date) = 2) D2
ON U.userID = D1.userID
LEFT JOIN (SELECT userID, NumberofLogins FORM tblLogins WHERE DAY(date) = x) Dx
ON U.userID = Dx.userID
...

OR

SELECT
userID
,SUM(CASE WHEN DAY(date) = 1 THEN NumberofLogins END) AS NumberofLoginsDate1
,SUM(CASE WHEN DAY(date) = 2 THEN NumberofLogins END) AS NumberofLoginsDate2
,SUM(CASE WHEN DAY(date) = x THEN NumberofLogins END) AS NumberofLoginsDatex
...

FROM tblLogins

WHERE MONTH(date) = 8

GROUP BY userID
Wietze314
  • 5,942
  • 2
  • 21
  • 40