【问题标题】:Get data of 2 different dates in 2 different columns sql在 2 个不同的列 sql 中获取 2 个不同日期的数据
【发布时间】:2021-04-21 13:38:05
【问题描述】:
我有一个 sql 表,其中包含 Name、VisitingDate、StayTime 列
我想要一个查询,它可以给我数据,其中 1 列我可以得到 thismonthvisit 的数据,其他列我可以得到 lastmonthvisit 的数据,在第 3 列我可以得到特定人的逗留时间总和的数据。
数据库表:--
| Name |
VisitingDate |
StayTime(in minutes) |
| A |
2021-04-20 |
5 |
| A |
2021-04-21 |
15 |
| A |
2021-03-20 |
10 |
| B |
2021-03-20 |
5 |
想要的结果:--
| Name |
Thismonthvisit |
TotalStayTimeThismonth(in minutes) |
LastmonthVisit |
TotalStayTimelastmonth(in minutes) |
| A |
2 |
20 |
1 |
10 |
| B |
0 |
0 |
1 |
5 |
【问题讨论】:
标签:
sql
sql-server
datetime
join
【解决方案1】:
这就是你要找的东西:
select name,
SUM(CASE WHEN FORMAT(VisitingDate, 'YYYYMM') = FORMAT(getdate(),'YYYYMM') THEN 1 ELSE 0 END) AS ThisMonthVisit,
SUM(CASE WHEN FORMAT(VisitingDate, 'YYYYMM') = FORMAT(getdate(),'YYYYMM') THEN StayTime ELSE 0 END) AS TotalStayTimeThisMonth,
SUM(CASE WHEN FORMAT(VisitingDate, 'YYYYMM') = FORMAT(dateadd(month, -1, getdate()),'YYYYMM') THEN 1 ELSE 0 END) AS LastMonthVisit,
SUM(CASE WHEN FORMAT(VisitingDate, 'YYYYMM') = FORMAT(dateadd(month, -1, getdate()),'YYYYMM') THEN StayTime ELSE 0 END) AS TotalStayTimeLastMonth
from MyTable
where FORMAT(VisitingDate, 'YYYYMM') > FORMAT(dateadd(month, -2, getdate()),'YYYYMM')
group by Name
SEE DEMO HERE
【解决方案2】:
你可以使用聚合:
select name,
sum(case when month(visitingdate) = month(getdate())
then 1 else 0
end) as cnt_thismonth,
sum(case when month(visitingdate) = month(getdate())
then staytime else 0
end) staytime_thismonth,
sum(case when month(visitingdate) <> month(getdate())
then 1 else 0
end) as cnt_lastmonth,
sum(case when month(visitingdate) <> month(getdate())
then staytime else 0
end) staytime_lastmonth
from t
where visitingdate >= dateadd(month, -1, datefromparts(year(getdate()), month(getdate()), 1))
group by name;