Counting Values based on distinct values from another Column

↘锁芯ラ 提交于 2019-12-08 01:20:23

问题


I need to calculate how many orderlines there are based on the orderlineNo being distinct. Each OrderNo is different BUT the OrderLineNo is the same for each order. i.e. 9 lines on a order then order lines number will go from 1 - 9. The same if on another order there are 3 orderlines they will go from 1 - 3

But in orderlineno there could be orderline numbers that are the same - for this I only want to count it once

Example:

OrderNo        OrderLineNo
987654             1
987654             2
987654             2
987654             3
987654             4
987654             5
987654             6
987654             7

The total order lines here is 7. There are two order lines with 2 and I want them to only be counted once.

Is this possible using SQL Server 2014.


回答1:


You can add DISTINCT to a COUNT:

select OrderNo, count(distinct OrderLineNo)
from tab
group by OrderNo;

Or if OrderLineNo always starts with 1 and increases without gaps:

select OrderNo, max(OrderLineNo)
from tab
group by OrderNo;

Edit:

Based on the comment it's not a count per OrderNo, but a global count. You need to use a Derived Table:

select count(*)
from
 (select distinct OrderNo, OrderLineNo
  from tab
 ) as dt;

or

select sum(n)
from
 (select OrderNo, max(OrderLineNo) as n
  from tab
  group by OrderNo
 ) as dt;

or

select sum(Dist_count)
from
 ( select OrderNo,count(distinct OrderLineNo) as Dist_count
   from Table1
   group by OrderNo
 ) as dt



回答2:


I guess you want this:

SELECT OrderNo, COUNT(distinct OrderLineNo) as CntDistOrderLineNoPerOrderNo
FROM Table1
GROUP BY OrderNo

demo

So for every OrderNo the count of dictinct OrderLineNo which is 7 for 987654.

If you instead want the sum of all distinct OrderLineNo as commented.

WITH CTE AS
(
  SELECT OrderNo,
         MAX(OrderLineNo) as MaxOrderLineNoPerOrderNo
  FROM Table1
  GROUP BY OrderNo
)
SELECT SUM(MaxOrderLineNoPerOrderNo) AS SumOrderLineNoPerOrderNo
FROM CTE

Demo




回答3:


Use Distinct in count aggregate

select count(distinct OrderLineNo) as Dist_count
from yourtable



回答4:


A solution without distinct, but it requires applying group by twice:

select orderNo , count(*) from
  (select orderNo from tbl group by orderNo,orderlineNo) t1 group by orderNo


来源:https://stackoverflow.com/questions/31478205/counting-values-based-on-distinct-values-from-another-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!