我有一个包含名称及其交易的数据集,如何获得比平均值更低的平均值和交易数量,并且低于平均值。
Name Transaction
John 12
John 34
John 45
John 66
John 32
chris 26
chris 54
chris 56
chris 99
chris 13
chris 4
kim 22
kim 34
kim 7
kim 11
kim 34
O / P将是
Name Avg Count_greater_than_Avg Count_Less_than_Avg
John 37.8 2 3
chris 42 3 3
kim 21.6 3 2
提前致谢..
答案 0 :(得分:2)
试试这个:
SELECT t1.Name, t2.Aver,
COUNT(CASE WHEN Transaction < Aver THEN 1 END) Count_Less_than_Avg,
COUNT(CASE WHEN Transaction > Aver THEN 1 END) Count_greater_than_Avg
FROM mytable AS t1
JOIN (
SELECT Name, AVG(Transaction * 1.0) AS Aver
FROM mytable
GROUP BY Name
) AS t2 ON t1.Name = t2.Name
GROUP By Name
您需要派生表才能计算每Name
的平均值。然后,您可以JOIN
原始表到此派生表并使用条件聚合来计算小于,大于的数字交易。
答案 1 :(得分:0)
这基本上首先使用相关查询添加列Your_Avg
,然后用另一个选择包装它以选择小于avg和更大倍数的出现次数。
SELECT tt.name,tt.Your_Avg,
count(CASE WHEN tt.Your_Avg > tt.Transaction then 1 end) as Greater_Then_Avg,
count(CASE WHEN tt.Your_Avg > tt.Transaction then 1 end) as Smaller_Then_Avg
FROM(
SELECT t.name,
(SELECT avg(s.transaction) FROM YourTable s WHERE s.name = t.name) as Your_Avg,
t.transaction
FROM YourTable) tt
GROUP BY tt.name