1

我有这些列的表:

userID, date, NumberofLogins

基本上记录用户在哪个日期登录了多少次。

如何使用 SQL 查询将其转换为具有以下表的表?

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

我只有一个月的数据,所以应该没问题。

4

2 回答 2

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
于 2013-09-09T08:40:08.750 回答
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
...

或者

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
于 2013-09-09T08:42:15.803 回答