Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Interesting COUNT() Problem..! Help much appreciated !

$
0
0

I have a function which checks the database to check if the customer exists or not and if it exists in the database the query calculates how many “Ship To” address is 

associated with the particular customer. This it calculates by counting the no of rows. Note: The system by default adds a blank row for each customer.

Here is the function:

CREATE FUNCTION [dbo].[ShipToNum] (@Org Varchar(100))

RETURNS Varchar(100)
AS
BEGIN

DECLARE @ShipToNo as Varchar(100)

SELECT  @ShipToNo = CASE WHEN COUNT(ST.ShipToNum) = 0 THEN 1 ELSE COUNT(ST.ShipToNum) END  
FROM [ICOERPSQL].[EpicorTest905].[dbo].[Customer] AS Cus INNER JOIN [ICOERPSQL].[EpicorTest905].[dbo].[ShipTo] AS ST ON Cus.CustNum = ST.CustNum
where Cus.CustID = @Org

Return @ShipToNo

END

GO

So now as you can see in the query, when the customer doesn't exist it will Count the no of rows as 0 and return 1. In case it exists, it will count the no of rows eg. if Customer 

abc has 4 "Ship To" address the query will return 5 including the blank row as mentioned in the note.

Now this function I am using in my main query to retrive some results:

CASE WHEN dbo.ShipToNum(dbo.CreateID(Org)) = 1 THEN ROW_NUMBER() OVER (PARTITION BY dbo.CreateID(Org) ORDER BY dbo.CreateID(Org)) ELSE dbo.ShipToNum(dbo.CreateID(Org)) END As ShipToNum2

Note:Here CreateID is just a function which generates unique ID's to customer.

When the customer doesn't exist the query will return 1 and partition the coloumn sequentially for same ID's.

For example:

Let there be a customer which doesn't exist in the database called abc having four "Ship To" address. The query will return the following result:

ID     -   ShipToNum

ABC      1
ABC      2
ABC      3
ABC      4

Now comes my question:

If the customer exists in the system for example: Customer DEF exists with two 'ShipTo' address then this query will return number 3 including the blank row. And lets suppose 
in today's report two 'ShipTo' address were added for this customer:

For the 3rd 'ShipTo' address this query will be perfect. The new line added will be"

ID - ShipToNum

DEF    3

But for the 4th 'ShipTo' address the query will again count 3 as the 3rd 'ShipTo' address was not imported in the database yet and it will result in:

(SCENARIO: Basically a report is generated and then using a tool the data will be imported so every row generated is not at the same time imported in the DB but it is inserted once the entire report is generated)
ID - ShipToNum

DEF  3 (this should have been 4 instead)

Now how should can keep a correct count of this considering the entire scenario ?

Thanks help much appriciated.


Vivek Kamath



Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>