如何在不重复的情况下有效地计算SQL中列值的出现次数?

时间:2019-02-20 08:19:06

标签: sql sql-server-2008-r2

发现计数时,我的计数为:

Serial No  |   Countt
------------------------
10467      |     1
10468      |     1
10468      |     2
10469      |     1

我要查询查找计数,如下所示:

Serial No  |  Countt
----------------------
10467      |     1
10468      |     2
10469      |     1

我在下面的查询中使用了

(SELECT Distinct Tax_Percentage, Serial_No, 
COUNT(*) OVER (PARTITION BY Tax_Percentage,Serial_No ) AS Countt
FROM sales_detail Where Serial_No>=10467)
Order By  Serial_No

enter image description here

3 个答案:

答案 0 :(得分:0)

从mytable GROUP BY属性中选择ID,属性,COUNT(属性)

This can help you

答案 1 :(得分:0)

按两列分组

SELECT Tax_Percentage, Serial_No, COUNT(*) Countt 
FROM sales_detail 
Where Serial_No>=10467) 
Group by Tax_Percentage, Serial_No
Order By Serial_No

我不确定您要达到什么目的,但是如果要查找serial_no的出现,则需要按此列对计数进行分区。

SELECT Tax_Percentage, Serial_No, 
        COUNT(*) over(partition by Serial_No) Countt 
FROM sales_detail 
Where Serial_No>=10467) 
Order By Serial_No

答案 2 :(得分:0)

尝试:由于Taxpercent,您知道我们无法获得唯一性,如果跳过该列,您会很容易得到:

SELECT distinct TaxPrcnt,SrNo,count(CAST(ISNULL(SrNo,0) as int)) OVER(PARTITION BY SrNo 
ORDER BY SrNo) AS Countt
FROM #temp

enter image description here