Put rows into columns

585 views Asked by At

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.

2

There are 2 answers

0
Wietze314 On BEST ANSWER

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
2
gvee On

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