我有这些列的表格:
userID, date, NumberofLogins
基本记录用户登录的次数。
如何使用SQL查询将其转换为包含以下内容的表?
UserID, NumberofLoginsDate1, NumberofLoginsDate2, ..., NumberofLoginsDate31.
我只有一个月的数据,所以这应该没问题。
答案 0 :(得分:0)
注意:假设为MySQL(因此使用Current_Date
函数,并非所有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
答案 1 :(得分:0)
也可以通过数据透视查询来完成。 重复Dx部分直到31.如果您的表有比8月更多的数据,也为此添加一个过滤器。 (月(日)= 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