我正在尝试编写一个有效的查询,以给出以下两个表来按月和user_group分组的已连接用户的百分比:
我正在使用MySQL。
谢谢。
答案 0 :(得分:1)
您基本上需要在用户ID列上连接2个表。然后只需按user_group和连接日期月份分组。您可以在SQL Server中使用DATEPART来做到这一点。
类似这样的东西:
SELECT u.user_group, DATEPART(MONTH, c.connection_date) AS month, COUNT(c.id)
FROM connections c INNER JOIN users u
ON c.user_id = u.user_id
GROUP BY u.user_group, DATEPART(MONTH, c.connection_date);
答案 1 :(得分:1)
我假设connections.connection _date和users.creation_date为日期时间。
要获得一个月内的连接用户百分比相对于该月的用户总数,请使用:
SELECT u.user_group, DATE_FORMAT(`c`.`connection_date`, "%M %Y") AS month,
COUNT(DISTINCT u.`user_id`) / (SELECT COUNT(`user_id`) FROM users WHERE users.creation_date <= adddate(last_day(`c`.`connection_date`), 1) AND users.user_group = u.user_group) AS percentage,
COUNT(DISTINCT u.`user_id`) as loggedThisMonth,
(SELECT COUNT(`user_id`) FROM users WHERE users.creation_date <= adddate(last_day(`c`.`connection_date`), 1) AND users.user_group = u.user_group) AS totalRegisteredToMonth
FROM connections c LEFT JOIN users u ON c.`user_id` = u.`user_id`
GROUP BY u.user_group, DATE_FORMAT(`c`.`connection_date`, "%M %Y")
ORDER BY DATE_FORMAT(`c`.`connection_date`, "%Y %m"), u.user_group ASC
此方法的工作原理:
COUNT(DISTINCT u.user_id)
(SELECT COUNT(
user_id ) FROM users WHERE users.creation_date <= adddate(last_day(
c .
连接为止_date ), 1) AND users.user_group = u.user_group)
参考:
adddate(last_day(`c`.`connection_date`), 1)
答案 2 :(得分:0)
查看此链接:cppreference。
这是sql:
Option Explicit
Public Sub StatusLetter()
SearchandScrape "Apple"
End Sub
Public Sub SearchandScrape(URL As String)
Dim IE As SHDocVw.InternetExplorer, headlines As Object, i As Long
Dim agenciesAndTime As Object, agencies As Object, times As Object, descriptions As Object
Set IE = New SHDocVw.InternetExplorer
With IE
.Visible = True
.Navigate2 "https://www.google.com/search?q=" & URL & "&tbm=nws&source=lnt&tbs=qdr:d&sa=X&ved=0ahUKEwjf_LHL1bngAhXqQ98KHTs2D4QQpwUIHw&biw=1282&bih=893&dpr=1"
While .Busy Or .readyState < 4: DoEvents: Wend
Set headlines = .document.querySelectorAll("h3.r")
Set agenciesAndTime = .document.querySelectorAll("h3.r + div span")
Set agencies = .document.querySelectorAll("h3.r + div span:nth-of-type(1)")
Set times = .document.querySelectorAll("h3.r + div span:nth-of-type(3)")
Set descriptions = .document.querySelectorAll("#ires div.st")
Dim results(), headers()
headers = Array("Headline", "Agency&Time", "Agency", "Time", "Description")
ReDim results(1 To headlines.Length, 1 To 5)
If headlines.Length > 0 Then
For i = 0 To headlines.Length - 1
results(i + 1, 1) = headlines.item(i).innerText
results(i + 1, 2) = agenciesAndTime.item(i).innerText
results(i + 1, 3) = agencies.item(i).innerText
results(i + 1, 4) = times.item(i).innerText
results(i + 1, 5) = descriptions.item(i).innerText
Next
End If
.Quit
With ThisWorkbook.Worksheets("Sheet1")
.Cells.ClearContents
.Cells(1, 1).Resize(1, UBound(headers) + 1) = headers
.Cells(2, 1).Resize(UBound(results, 1), UBound(results, 2)) = results
End With
End With
End Sub
随时进行编辑