SQL Server Count最频繁数据的实例

时间:2018-09-10 08:04:20

标签: sql sql-server

我不认为我需要做的太复杂了, 但是嘿,是星期一早上,我可以使用一些建议。 基本上,我在SQL Server中以以下格式进行汇总查询:

SELECT [Data1], COUNT(*), MAX([Data2])
FROM [Source]
GROUP BY [Data1]

但是我也需要第四个领域。 一个字段,用于计算值MAX([Data2])出现的次数。

在这里我将做一个简单的例子:

|Data 1|Data 2|
|1     |x     |
|3     |p     |
|1     |z     |
|3     |f     |
|1     |x     |
|1     |b     |
|2     |h     |
|1     |o     |
|2     |h     |
|1     |x     |
|3     |f     |
|2     |h     |
|1     |z     |

需要产生输出:

|Data1|Count|Max|Occurances|
|1    |7    |x  |3         |
|2    |3    |h  |3         |
|3    |3    |f  |2         |

任何帮助将不胜感激。

4 个答案:

答案 0 :(得分:2)

您要查找的内容在统计信息中具有名称。您需要模式和模式的频率。

我将使用两种聚合方法来解决此问题:

{{1}}

答案 1 :(得分:0)

类似的事情应该有所帮助-

>>> x = 'abcd efgh ijkl'
>>> x[-8:1]
''          

注意:我会避免使用library(plotly) library(quantmod) # Download some data getSymbols(Symbols = c("AAPL", "MSFT")) ds <- data.frame(Date = index(AAPL), AAPL[,6], MSFT[,6]) plot_ly(ds, x = ~Date) %>% add_lines(y = ~AAPL.Adjusted, name = "Apple") %>% add_lines(y = ~MSFT.Adjusted, name = "Microsoft") %>% layout( title = "Stock Prices", xaxis = list(rangeslider = list(type = "date")), yaxis = list(title = "Price")) 作为列名/别名。

答案 2 :(得分:0)

您可以尝试将窗口功能$('#cities').change(function(e){ var $option = $('#cities2 option'); var $selectedValue = $('#cities option:selected').val(); $.each($option, function(inedx, option){ var disabled = $selectedValue !== $(option).val(); $(option).prop('disabled', disabled); }); }); 结合使用。

使用cteCTE列中的COUNT获得Occurances [Data 1]。然后使用另一个[Data 2] desc按CTE2 desc进行行号排序,这表示最大数量。

Occurances

sqlfiddle

结果

;with cte as (
SELECT [Data 1],
       [Data 2],
       COUNT(*) OVER (PARTITION BY [Data 1] ORDER BY [Data 1]) [count],
       COUNT(*) OVER (PARTITION BY [Data 2],[Data 1] ORDER BY [Data 2]) Occurances
FROM T
),cte2 as (
    SELECT  
        [Data 1], 
        [Data 2],
        [count],
        Occurances,row_number() over(partition by [Data 1] order by Occurances desc) rn
    FROM cte
)

select  [Data 1], 
        [Data 2],
        [count], 
        Occurances
from cte2
where rn = 1

答案 3 :(得分:0)

您可以尝试一下。

DECLARE @Source AS TABLE([Data1] INT,[Data2] VARCHAR(5))
INSERT INTO @Source VALUES
(1, 'x'), 
(3, 'p'),
(1, 'z'),
(3, 'f'),
(1, 'x'),
(1, 'b'),
(2, 'h'),
(1, 'o'),
(2, 'h'),
(1, 'x'),
(3, 'f'),
(2, 'h'),
(1, 'z')

;WITH T AS (
SELECT [Data1] , 
    COUNT(*) OVER(PARTITION BY [Data1]) [Count], 
    [Data2],    
    COUNT(*) OVER(PARTITION BY [Data2]) Occurances
FROM @Source
)
SELECT TOP 1 WITH TIES [Data1], [Count], [Data2] [Max], Occurances
FROM T 
ORDER BY ROW_NUMBER() OVER (PARTITION BY [Data1] ORDER BY Occurances DESC) 

结果:

Data1       Count       Max   Occurances
----------- ----------- ----- -----------
1           7           x     3
2           3           h     3
3           3           f     2