How do I count the amount of items in a repeated field?

Asked

Viewed 49 times

0

I have a table with the Ctrlcarganum field that has a record of the cargo number of a truck. I need to make a consultation that brings the total of this field. Until I could make the consultation see:

SELECT COUNT (*) CtrlCargaNum 
FROM CTRL_CARGA 
WHERE CtrlCargaData BETWEEN '2018-01-01' AND '2018-01-04' AND EmpCod = '01.01'

Only it counts only the records that are on these dates.

I would like him to take the repeating charge number and count as 1 CHARGE

Ex: 
CtrlCargaNum = 1001
CtrlCargaNum = 1001

 = 1 CARGA

CtrlCargaNum = 1002
CtrlCargaNum = 1002
CtrlCargaNum = 1002

 = 1 CARGA

and add these charges: 1 LOAD + 1 LOAD = 2. I am using mysql server inserir a descrição da imagem aqui

2 answers

1

You could do something like:

SELECT COUNT(c.CtrlCargaNum) CtrlCargaNum 
FROM (SELECT DISTINCT CtrlCargaNum FROM CTRL_CARGA WHERE CtrlCargaData BETWEEN 
'2018-01-01' AND '2018-01-04' AND EmpCod = '01.01') c

0

Mysql and SQL Server tags are marked. Follows solution for SQL Server, but the use of DISTINCT is also valid for Mysql.

-- código #1
SELECT count(distinct CtrlCargaNum) as Qtd
  from CTRL_CARGA 
  where CtrlCargaData between '2018-01-01' and '2018-01-04'
        and EmpCod = '01.01';
  • Gives the same problem as before. It has to show 19 loads but shows a total of 26

  • @Felipemichaeldafonseca I tested the above code in both SQL Server 2017 and Mysql 5.6 and both worked. See http://sqlfiddle.com/#! 18/42138/1 and http://sqlfiddle.com/#! 9/ea2c5f5/2

Browser other questions tagged

You are not signed in. Login or sign up in order to post.