假设我有一张桌子:
yr mo user visits
2015 11 A 3
2015 11 A 3
2015 11 B 4
2015 11 B 4
2015 11 B 4
2015 11 C 3
2015 12 A 6
2015 12 A 2
2015 12 B 1
2015 12 C 6
我需要汇总到:
yr mo visitor min max cntmin cntmax
2015 11 3 3 4 2 1
2015 12 3 1 6 1 2
其中,vistor是每月唯一身份访问者的数量,min是每月最大访问次数,max是每月最大用户数,cntmin和cnt max是最小和最大用户数(分别) )。
除了cntmin和cntmax之外,我在聚合表中有所有列。我似乎无法弄清楚如何找到他们。任何帮助都将不胜感激。我正在使用tansact sql。
答案 0 :(得分:1)
我会使用两个级别的聚合来处理这个问题:
.row {
width: 100%;
display: flex;
flex-wrap: wrap;
justify-content: center;
}
button {
width: 200px;
}
答案 1 :(得分:0)
尝试(旧的和不正确的):
SELECT yr, mo, COUNT(DISTINCT user) AS visitor
, MIN(visits) AS min
, MAX(visits) AS max
, COUNT(CASE WHEN visits = MIN(visits) THEN 1 ELSE NULL END) AS cntMin
, COUNT(CASE WHEN visits = MAX(visits) THEN 1 ELSE NULL END) AS cntMax
FROM TableName
GROUP BY yr, mo
新(后期建议):
SELECT A.yr, A.mo, A.visitor, A.min, A.max
, (SELECT B.yr, B.mo, COUNT(B.visits) FROM TableName AS B WHERE B.yr = A.yr AND B.mo = A.mo AND B.visits = A.min GROUP BY B.yr, B.mo) AS cntMin
, (SELECT C.yr, C.mo, COUNT(C.visits) FROM TableName AS C WHERE C.yr = A.yr AND C.mo = A.mo AND C.visits = A.max GROUP BY C.yr, C.mo) AS cntMax
FROM
(SELECT TableName.yr, TableName.mo, COUNT(DISTINCT TableName.user) AS visitor
, MIN(visits) AS min
, MAX(visits) AS max
FROM TableName
GROUP BY yr, mo) AS A