Get AVG ignoring Null or Zero values

NULL is already ignored so you can use NULLIF to turn 0 to NULL. Also you don’t need DISTINCT and your WHERE on ActualTime is not sargable. SELECT AVG(cast(NULLIF(a.SecurityW, 0) AS BIGINT)) AS Average1, AVG(cast(NULLIF(a.TransferW, 0) AS BIGINT)) AS Average2, AVG(cast(NULLIF(a.StaffW, 0) AS BIGINT)) AS Average3 FROM Table1 a WHERE a.ActualTime >= ‘20130401’ AND a.ActualTime … Read more

Why is there a HUGE performance difference between temp table and subselect

Why it’s not recommended to use subqueries? Database Optimizer (regardless of what database you are using) can not always properly optimize such query (with subqueries). In this case, the problem to the optimizer is to choose the right way to join result sets. There are several algorithms for joining two result sets. The choice of … Read more

T-SQL split string based on delimiter

May be this will help you. SELECT SUBSTRING(myColumn, 1, CASE CHARINDEX(“https://stackoverflow.com/”, myColumn) WHEN 0 THEN LEN(myColumn) ELSE CHARINDEX(“https://stackoverflow.com/”, myColumn) – 1 END) AS FirstName ,SUBSTRING(myColumn, CASE CHARINDEX(“https://stackoverflow.com/”, myColumn) WHEN 0 THEN LEN(myColumn) + 1 ELSE CHARINDEX(“https://stackoverflow.com/”, myColumn) + 1 END, 1000) AS LastName FROM MyTable

IntelliSense is not working in SQL Server Management Studio

You can try solution from these questions1 or questions2 and questions3. Or please try these steps as below: Enable IntelliSense: For all query windows, please go to Tools >> Options >> Text Editor >> Transact-SQL >> IntelliSense, and select Enable IntelliSense. For each opening query window, please go to Query >> Intellisense Enabled. Enable statement … Read more

How to find out what is locking my tables?

Take a look at the following system stored procedures, which you can run in SQLServer Management Studio (SSMS): sp_who sp_lock Also, in SSMS, you can view locks and processes in different ways: Different versions of SSMS put the activity monitor in different places. For example, SSMS 2008 and 2012 have it in the context menu … Read more

How to use a CTE statement in a table-valued function in SQL Server

Syntax for the CTE in table valued function would be: CREATE FUNCTION GetDistributionTable ( @IntID int, @TestID int, @DateFrom datetime, @DateTo datetime ) RETURNS TABLE AS RETURN ( WITH cte AS ( SELECT ROUND(Result – AVG(Result) OVER(), 1) Result FROM RawResults WHERE IntID = @IntID AND DBTestID = @TestID AND Time >= @DateFrom AND Time … Read more