SQLSERVER removing duplicate values for a column and displays all the data \ the DISTINCT deduplication \ the ISNULL () request SUM () \ NOT EXISTS using

Entered, preparing our test data

1. We want to filter data to remove duplicates and GX columns of all data displayed, as shown:

1 select t.* from [PeopleCount] as t where t.procedureID='8334'

2. Under this situation we are not using DISTINCT come heavy, we can try:

  First, the simple query this column with a distinct GX is no problem

1 select distinct t.GX from [PeopleCount] as t where t.procedureID='8334'

  But if we add other data in the table, then we have to look at the results:

1 select distinct t.GX ,t.* from [PeopleCount] as t where t.procedureID='8334'

  Obviously, it found that the data is not what we want.

3. This time we both want to go heavy, heavy going to want data, we can:

1 select t.* from [PeopleCount] as t where t.procedureID='8334' and not exists
2     (select 1 from [PeopleCount] where GX=t.GX and countID>t.countID)

  This is the GX filter all data de-duplication to the query.

Note: ①.EXISTS (sql returns the result set to true) NOT EXISTS (sql does not return a result set to true (or false return result sets))

       ②.EXISTS represents existential quantifier: subqueries with EXISTS does not return any data record, return only the logical value "True" or "False"

    . ③ correlated subquery execution process: first take "[PeopleCount] table" recorded in the first row in the outer query, the inner query processing attribute value associated with the record (in the inner layer given the WHERE clause) when the outer WHERE clause return "TRUE" value, then this record into the result table. Then the next line recording; repeat the process until the outer table records all the time until the traverse.

       ④.EXISTS statement does not care about the specific content of sub-queries, with "SELECT *", "Exists + subquery" is used to determine whether the sub-query returns records.

       ⑤.Exists: If the sub-query result set is not empty, returns "True"; if the subquery result set is empty, it returns "False".
                NOT EXISTS: If the subquery result is empty, return "TRUE" value; if the sub-query result set is not empty, return to "FALSE.

4. The results of the query (DJ column) if empty without summation:

1 select 
2 ISNULL((Select sum(DJ) as CountNum  FROM [PeopleCount] t WHERE type = 1 and t.procedureID='8334' and not exists
3 (select 1 from [PeopleCount] where GX=t.GX and countID>t.countID)),0)  as 求和结果

Note: ①.isnull (parameter 1, parameter 2), to determine whether a parameter is NULL, and if so, return parameter 2, parameter 1 otherwise.

        . ② SUM()a function for calculating a set of values or the sum of expression, SUM()the syntax of the following functions:SUM(DISTINCT expression)

  

To this end, thank you ~

 

Guess you like

Origin www.cnblogs.com/guozhaoxin/p/11888591.html