sql - Counting Values based on distinct values from another Column -


i need calculate how many orderlines there based on orderlineno being distinct. each orderno different orderlineno same each order. i.e. 9 lines on order order lines number go 1 - 9. same if on order there 3 orderlines go 1 - 3

but in orderlineno there orderline numbers same - want count 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 7. there 2 order lines 2 , want them counted once.

is possible using sql server 2014.

you can add distinct count:

select orderno, count(distinct orderlineno) tab group orderno; 

or if orderlineno starts 1 , increases without gaps:

select orderno, max(orderlineno) tab group orderno; 

edit:

based on comment it's not count per orderno, global count. need use derived table:

select count(*)  (select distinct orderno, orderlineno   tab  ) dt; 

or

select sum(n)  (select orderno, max(orderlineno) n   tab   group orderno  ) dt; 

or

select sum(dist_count)  ( select orderno,count(distinct orderlineno) dist_count    table1    group orderno  ) dt 

Comments