Multiple PIVOTS? Need to count by Hour Per Month(多个枢轴?每月需要按小时计算)
问题描述
这应该很简单.我有其他 PIVOT SQL 查询工作正常.我想计算登录次数:按小时、按月.我在想两个 PIVOT 还是 UNPIVOT 然后 PIVOT?是的,我已经在这里、其他网站、Google 等进行了挖掘.我被困住了.
这里是 SQLFiddle 演示(使用 案例
)
这是 SQLFiddle 演示(使用 PIVOT)
This should be pretty simple. I have other PIVOT SQL queries working fine. I want to count logins: by hour, by month. I am thinking two PIVOTs or UNPIVOT and then PIVOT? Yes, I have dug around here, other sites, Google, etc. I am pretty stuck.
SELECT
loginid
,DATEPART(MONTH,logtime) Month
, DATEPART(HOUR, logtime) Hour
FROM somelog (nolock)
) temp
PIVOT (
COUNT(loginid)
FOR Month in (JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC)
) AS Pvt
What I want the results to be..
HOUR,JAN,FEB,MAR
00
01
02
..
23
and I don't need 8760 (365 x 24) of them
I have tried GROUP BY HOUR
I have tried GROUP BY temp.hour
I have also tried this as well.. It does seem to work, but I get Hour 00 for example 365 times.. Again, the GROUP BY issue..
Thanks,
Kent
解决方案 One way to do it
or with PIVOT
Sample output for both queries:
| HOUR | JAN | FEB | MAR | APR | MAY | JUN | JUL | AUG | SEP | OCT | NOV | DEC |
|------|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|
| 0 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 2 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 3 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 4 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
...
Here is SQLFiddle demo (using CASE
)
Here is SQLFiddle demo (using PIVOT
)
这篇关于多个枢轴?每月需要按小时计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!