European Windows 2012 Hosting BLOG

BLOG about Windows 2012 Hosting and SQL 2012 Hosting - Dedicated to European Windows Hosting Customer

SQL Server 2016 Hosting - HostForLIFE.eu :: SQL Server Full Text Search with rank values

clock September 14, 2016 20:56 by author Peter

OnceSQL Server Full-Text Search with rank values  I wrote a post titled enabling Fulltext search in Azure SQL database discussing Full-Text search in Azure. while using it with one of my databases, needed to show the result of the search ordered by however well they match to the search criteria. in order to sort the result as i need, the best is, get a rank generated for every row and use it for ordering the result. I had used Freetext operate for obtaining the result but if i realized that this can not be achieved using the Freetext function.

The CONTAINSTABLE and FREETEXTTABLE functions return a column named Rank for showing the rank related to the record based on matching. this can be used get the result sorted based on it, showing most relevant records at the top. Remember, the higher value of the Rank generated indicates the best matching.

Now, write the following code:
view plainprint?

    -- Creating a table  
    CREATE TABLE dbo.EmployeeDetails  
    (  
     EmployeeDetailsId int identity(1,1) not null  
     , constraint pk_EmployeeDetails primary key (EmployeeDetailsId)  
     , WorkingExperience nvarchar(4000) not null  
     , ProjectsWorked nvarchar(4000) not null  
     , Resume nvarchar(max)   
    )  
    GO  
      
    CREATE FULLTEXT CATALOG EmployeeCatelog;  
    GO  
      
    CREATE FULLTEXT INDEX ON dbo.EmployeeDetails   
     (WorkingExperience, ProjectsWorked, Resume) KEY INDEX pk_EmployeeDetails  
     ON EmployeeCatelog;  
     -- By default CHANGE_TRACKING = AUTO  
      
      
    -- Once enabled, search can be performed;  
    SELECT *  
    FROM dbo.EmployeeDetails  
    WHERE freetext ((WorkingExperience, ProjectsWorked, Resume), 'SQL');  
      
    SELECT *  
    FROM dbo.EmployeeDetails  
    WHERE freetext ((Resume), 'SQL');  
      
    -- Get the rank and sort the result using it  
    SELECT t.Rank, e.*  
    FROM dbo.EmployeeDetails e  
     INNER JOIN CONTAINSTABLE (dbo.EmployeeDetails, (WorkingExperience, ProjectsWorked, Resume), 'SQL') AS t  
      ON e.EmployeeDetailsId = t.[Key]  
    ORDER BY t.Rank DESC  

HostForLIFE.eu SQL 2016 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



SQL Server 2012 Hosting - HostForLIFE.eu :: How to Upload Excelsheet Data In SQL Server Table?

clock September 7, 2016 23:24 by author Peter

In This code snippet, i will tell you about how Uploading Excelsheet Data in SQL Server Table. Now, write the followind code:

protected void btnSend_Click(object sender, EventArgs e) { 
    try { 
        string path = string.Concat(Server.MapPath("~/File/" + fileuploadExcel.FileName)); 
        fileuploadExcel.SaveAs(path); 
        string connExcelString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", path); 
        OleDbConnection excelConnection = new OleDbConnection(connExcelString); 
        OleDbCommand cmd = new OleDbCommand("Select [Name],[Mobile],[Email],[City],[DataId],[Date],[Source] from [Sheet1$]", excelConnection); 
        excelConnection.Open(); 
        OleDbDataReader dReader; 
        dReader = cmd.ExecuteReader(); 
        SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection); 
        SqlBulkCopyColumnMapping mapName = new SqlBulkCopyColumnMapping("Name", "Name"); 
        sqlBulk.ColumnMappings.Add(mapName); 
        SqlBulkCopyColumnMapping mapMobile = new SqlBulkCopyColumnMapping("Mobile", "Mobile"); 
        sqlBulk.ColumnMappings.Add(mapMobile); 
        SqlBulkCopyColumnMapping mapEmail = new SqlBulkCopyColumnMapping("Email", "Email"); 
        sqlBulk.ColumnMappings.Add(mapEmail); 
        SqlBulkCopyColumnMapping mapCity = new SqlBulkCopyColumnMapping("City", "City"); 
        sqlBulk.ColumnMappings.Add(mapCity); 
        //SqlBulkCopyColumnMapping mapState = new SqlBulkCopyColumnMapping("State", "State"); 
        //sqlBulk.ColumnMappings.Add(mapState); 
        SqlBulkCopyColumnMapping mapDataId = new SqlBulkCopyColumnMapping("DataId", "DataId"); 
        sqlBulk.ColumnMappings.Add(mapDataId); 
        SqlBulkCopyColumnMapping mapAmount = new SqlBulkCopyColumnMapping("Date", "Date"); 
        sqlBulk.ColumnMappings.Add(mapAmount); 
        SqlBulkCopyColumnMapping mapSource = new SqlBulkCopyColumnMapping("Source", "Source"); 
        sqlBulk.ColumnMappings.Add(mapSource); 
        //Give your Destination table name 
        sqlBulk.DestinationTableName = "UploadedExcelData"; 
        sqlBulk.WriteToServer(dReader); 
        excelConnection.Close(); 
        UpdateRecords(); 
        lblMsg.Text = "File Data Uploaded Successfully... "; 
        File.Delete(path); 
    } catch (Exception ex) { 
        lblMsg.Text = "Something Went Wrong... Plz Check Excel File "; 
        //string script = "<script>alert('" + ex.Message + "');</script>"; 
    } 
}

HostForLIFE.eu SQL Server 2012 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.



AngularJS Hosting - HostForLIFE.eu :: Ng-options from other Uses of Same ng-Options

clock August 23, 2016 21:54 by author Peter

In this post, i will tell you about ng ng-options instance but remove the selected items from previous uses in Angularjs. Now write the following code:

    <!DOCTYPE html> 
    <html> 
     
    <head> 
        <title></title> 
        <meta charset="utf-8" /> 
        <script src="Scripts/angular.js"></script> 
        <link href="Content/bootstrap.css" rel="stylesheet" /> 
        <script> 
    var app = angular.module('myApp', []); 
    app.controller('demoCtrl', function ($scope) 
    { 
        $scope.options = [ 
        { 
            name: 'Apple', 
            id: '1' 
        }, 
        { 
            name: 'Orange', 
            id: '2' 
        }, 
        { 
            name: 'Banana', 
            id: '3' 
        }, 
        { 
            name: 'Pear', 
            id: '4' 
        }, ]; 
    }); 
        </script> 
    </head> 
     
    <body> 
        <div ng-app="myApp" ng-controller="demoCtrl"> 
            <div class="form-group col-md-3"> 
                <label for="select1">Select 1:</label> 
                <select ng-model="newForm.select1" ng-options="option.name as option.name for option in options" class="form-control"> 
                    <option value=""></option> 
                </select> 
            </div> 
            <div class="row"> 
                <br> </div> 
            <div class="form-group col-md-3"> 
                <label for="select2">Select 2:</label> 
                <select ng-model="newForm.select2" ng-options="option.name as option.name for option in options | filter: newForm.select1 && {name: '!' + newForm.select1}" class="form-control"> 
                    <option value=""></option> 
                </select> 
            </div> 
        </div> 
    </body> 
     
    </html> 

 

HostForLIFE.eu AngularJS Hosting

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.



SQL Server 2012 Hosting - HostForLIFE.eu :: SQL Queries for Database Analysis

clock August 11, 2016 21:32 by author Peter

In this post, I'll share few useful SQL queries for database analysis on SQL Server 2012. I shared few SQL queries useful in analyzing database, which I use quite often. This query will return all table names and no.of rows in it for built-in tables.

    -- List all table names and number of rows in it for user-defined tables 
    SELECT distinct t.name,prt.rows 
    FROM sys.tables t INNER JOIN sys.partitions AS prt 
    ON t.object_id = prt.object_id where t.is_ms_shipped=1 -- 0 for user-defined tables 
    order by prt.rows desc 


This query will return column names and its data type of a table.
    -- Get column names and its types of a table 
    SELECT cols.name,t.name 
    FROM sys.objects o join sys.columns cols on o.object_id= cols.object_id 
    join sys.types t on t.system_type_id=cols.system_type_id 
    and o.name='Employee'-- Table Name


This query will return file name, its size and file group name of a database.
    SELECT sdf.name AS [FileName], 
    size/128 AS [Size], 
    fg.name AS [File_Group_Name] 
    FROM sys.database_files sdf 
    INNER JOIN 
    sys.filegroups fg 
    ON sdf.data_space_id=fg.data_space_id 


Batch file to execute all sql files in a directory, Save it as .bat in a folder that have sql script files to be executed.
    @Echo Off 
    FOR /f %%i IN ('DIR *.Sql /B') do call :RunSql %%i 
    GOTO :END 
    :RunSql 
    Echo Executing SQL: %1 
    SQLCMD -S server1 -U user1 -P pwd1 -d DB1 -i %1 
    Echo Completed SQL: %1 
    :END 


This query will return all table names that have a Foreign key:
    SELECT SCHEMA_NAME(schema_id) AS SchemaName, 
    name AS TableName 
    FROM sys.tables where OBJECTPROPERTY(OBJECT_ID,'TableHasForeignKey') = 1 -- Return all

HostForLIFE.eu SQL Server 2012 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.



SQL Server 2016 Hosting - HostForLIFE.eu :: How to Use sys.dm_os_performance_counters to get your Buffer cache hit ratio?

clock July 28, 2016 23:23 by author Peter

Today, I will show you How to Use sys.dm_os_performance_counters to get your Buffer cache hit ratio. In order to calculate the Buffer cache hit ratio we need to query the sys.dm_os_performance_counters dynamic management view. There are 2 counters we need in order to do our calculation, one counter is Buffer cache hit ratio and the other counter is Buffer cache hit ratio base. We divide Buffer cache hit ratio base by Buffer cache hit ratio and it will give us the Buffer cache hit ratio.

Here is the query that will do that, this query will only work on SQL Server 2005 and up.
SELECT (a.cntr_value * 1.0 / b.cntr_value) * 100.0 AS BufferCacheHitRatio
FROM sys.dm_os_performance_counters  a
JOIN  (SELECT cntr_value,OBJECT_NAME

FROM sys.dm_os_performance_counters 
WHERE counter_name = 'Buffer cache hit ratio base'
AND OBJECT_NAME = 'SQLServer:Buffer Manager') b ON  a.OBJECT_NAME = b.OBJECT_NAME
WHERE a.counter_name = 'Buffer cache hit ratio'

AND a.OBJECT_NAME = 'SQLServer:Buffer Manager'

Page life expectancy
Now let's look at Page life expectancy. Page life expectancy is the number of seconds a page will stay in the buffer pool, ideally it should be above 300 seconds. If it is less than 300 seconds this could indicate memory pressure, a cache flush or missing indexes.

Here is how to get the Page life expectancy
SELECT *
FROM sys.dm_os_performance_counters
WHERE counter_name = 'Page life expectancy'

HostForLIFE.eu SQL 2016 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



SQL Server 2014 Hosting - HostForLIFE.eu :: Calculate Total Rows in SQL Server 2014

clock June 24, 2016 22:15 by author Anthony

In this tutorial, I will write an article about How to Calculate Total Rows Inserted per Second in SQL Server 2014. Ever expected to compute the quantity of columns embedded consistently, for each table in every database on a server? Alternately, have you ever expected to approve that all methods have quit keeping in touch with tables? These sorts of inquiries come up routinely for me. To help with this, I've composed the following script, which inspects metadata qualities utilizing sys.partitions. This system isn't as precise as running SELECT COUNT(*) FROM, however its much quicker.

Remember, since it’s just looking at row counts, its very little help on tables that have a considerable measure of update/delete  action. Yet it does what I need it to do, and I utilize it pretty frequently, so I thought I'd experience case any other individual can advantage from it as well.

/* Declare Parameters */

DECLARE @newBaseline BIT = 1 -- change to 0 when you don't want to replace the baseline, i.e. after initial run
  , @delay CHAR(8) = '00:00:30'; -- change as needed 
IF @newBaseline = 1
BEGIN
    IF OBJECT_ID('tempdb..#baseline') IS NOT NULL
        DROP TABLE #baseline; 
    CREATE TABLE #baseline
    (
         database_name  SYSNAME
       , table_name     SYSNAME
       , table_rows     BIGINT
       , captureTime    DATETIME NULL
    );
END 

IF OBJECT_ID('tempdb..#current') IS NOT NULL
    DROP TABLE #current;
 CREATE TABLE #current
(
     database_name  SYSNAME
   , table_name     SYSNAME
   , table_rows     BIGINT
   , captureTime    DATETIME NULL
); 
IF @newBaseline = 1
BEGIN
    EXECUTE sp_MSforeachdb 'USE ?;
        INSERT INTO #baseline
        SELECT DB_NAME()
            , o.name As [tableName]
            , SUM(p.[rows]) As [rowCnt]
            , GETDATE() As [captureTime]
        FROM sys.indexes As i
        JOIN sys.partitions As p
            ON i.[object_id] = p.[object_id]
           AND i.index_id  = p.index_id
        JOIN sys.objects As o
            ON i.[object_id] = o.[object_id]
        WHERE i.[type] = 1
        GROUP BY o.name;' 
    WAITFOR DELAY @delay;
END
 EXECUTE sp_MSforeachdb 'USE ?;
INSERT INTO #current
SELECT DB_NAME()
    , o.name As [tableName]
    , SUM(p.[rows]) As [rowCnt]
    , GETDATE() As [captureTime]
FROM sys.indexes As i
JOIN sys.partitions As p
    ON i.[object_id] = p.[object_id]
   AND i.index_id  = p.index_id
JOIN sys.objects As o
    ON i.[object_id] = o.[object_id]
WHERE i.[type] = 1
GROUP BY o.name;' 
SELECT  c.*
      , c.table_rows - b.table_rows AS 'new_rows'
      , DATEDIFF(second, b.captureTime, c.captureTime) AS 'time_diff'
      , (c.table_rows - b.table_rows) / DATEDIFF(second, b.captureTime, c.captureTime) AS 'rows_per_sec'
FROM #baseline AS b
JOIN #current AS c
    ON b.table_name = c.table_name
   AND b.database_name = c.database_name
ORDER BY new_rows DESC;

 

HostForLIFE.eu SQL Server 2014 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



SQL Server 2016 Hosting - HostForLIFE.eu :: How to Export to Excel in c# from list and using Linq filter?

clock June 22, 2016 22:03 by author Peter

Today, let me explain you about Export to Excel in c# from list and using Linq filter. You will find lot export to excel coding in other website. I'm not going to give any new in this. I am also giving here with simple List collection with basic LINQ filter and export to excel sheet.
Note: Include the Microsoft.Office.Interop.Excel in your project.

List Collection With LINQ Filter:
    Eg: lstLocal = lstFlspc.Where(m => m.ClientLocation == “Chennai”).ToList();

Export to Excel in c#.net with List and LINQ Filter Query:
    public void ExportToExcel(List<FileInfoLocal> lst)
    {
        try
        {
//Filter in List collection
          lstLocal = lstFlspc.Where(m => m.ClientPath.Path == child.Text).ToList();


          Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();

          if (xlApp == null)
          {
              MessageBox.Show("Excel is not properly installed!!");
              return;
          }   

          Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
          Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
          object misValue = System.Reflection.Missing.Value;

          xlWorkBook = xlApp.Workbooks.Add(misValue);
          xlWorkSheet =(Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
             

          int iRow = 1, iColumn = 1;
          //Header Test
          xlWorkSheet.Cells[iRow, iColumn] = "Column1 Name";
          xlWorkSheet.Cells[iRow, iColumn + 1] = "Column2 Name";
          xlWorkSheet.Cells[iRow, iColumn + 2] = "Column3 Name";
          xlWorkSheet.Cells[iRow, iColumn + 3] = "Column4 Name";
          xlWorkSheet.Cells[iRow, iColumn + 4] = "Column5 Name";
          iRow++;

// Filter in List collection using LINQ

          if (lstLocal!= null)
          {
          foreach (var item in lstLocal)
            {
              // .. Add other parameters here. Body Text
              xlWorkSheet.Cells[iRow, iColumn] = item.Name;
              xlWorkSheet.Cells[iRow, iColumn + 1] = item.Date;
              xlWorkSheet.Cells[iRow, iColumn + 2] = item.Path;
              xlWorkSheet.Cells[iRow, iColumn + 3] = item.UserName;
              xlWorkSheet.Cells[iRow, iColumn + 4] = item.Desc;
              iRow++;                                  
            }
          }

         string sExcelFile = Directory.GetCurrentDirectory() + "Report.xls";

         xlWorkBook.SaveAs(sExcelFile, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
         xlWorkBook.Close(true, misValue, misValue);
         xlApp.Quit();

         releaseObject(xlWorkSheet);
         releaseObject(xlWorkBook);
         releaseObject(xlApp);

         MessageBox.Show("Excel file created successfully , you can find the file " + sExcelFile, "Export To Excell");

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }



    // Release the Excel object from memory
    private void releaseObject(object obj)
    {
        try
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
            obj = null;
        }
        catch (Exception ex)
        {
            obj = null;
            MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
        }
        finally
        {
            GC.Collect();
        }
    }

HostForLIFE.eu SQL 2016 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



SQL Server 2016 Hosting - HostForLIFE.eu :: How to Remove DataBase In Sql Server Without Using Wizard?

clock June 21, 2016 22:08 by author Peter

Today, I will explain you about how to Remove DataBase In Sql Server Without Using Wizard. This system stored procedure will helps you.
exec sp_dbremove 'dataBaseName'


The following is the entire script of the stored procedure:
USE [TMS] 
GO 
/****** Object:  StoredProcedure [sys].[sp_dbremove]    Script Date: 08-12-2014 22:09:09 ******/ 
SET ANSI_NULLS ON 
GO 
SET QUOTED_IDENTIFIER ON 
GO 
ALTER procedure [sys].[sp_dbremove] --- 1996/04/08 00:00 
    @dbname sysname = null, 
    @dropdev varchar(10) = null 
as 
    declare @dbid int 
    declare @devname sysname 
    declare @physname varchar(255) 
 
    if @dbname is null 
    begin 
        raiserror(15131,-1,-1) 
        return(1) 
    end 
 
    if lower(@dropdev) <> 'dropdev' and @dropdev is not null 
    begin 
        raiserror(15131,-1,-1) 
        return(1) 
    end 
 
    -- You must be SA to execute this sproc. 
    if (not (is_srvrolemember('sysadmin') = 1)) 
    begin 
        raiserror(15247,-1,-1) 
        return(1) 
    end 
 
    -- Make sure not trying to remove within a transaction. 
    set implicit_transactions off 
    if @@trancount > 0 
    begin 
        raiserror(15002,-1,-1,'sys.sp_dbremove') 
        return(1) 
    end 
 
    -- Check to see if database exists. 
    select @dbid = dbid from master.dbo.sysdatabases where name=@dbname 
    if @dbid is null 
    begin 
        raiserror(15010,-1,-1,@dbname) 
        return(1) 
    end 
 
    -- Make sure no one is in the db. 
    if (select count(*) from master.dbo.sysprocesses where dbid = @dbid) > 0 
    begin 
        raiserror(15069,-1,-1) 
        return (1) 
    end 
 
    -- Note: database @dbname may not exist anymore 
    -- If invoke gets error, exception will abort this proc. 
    EXEC %%DatabaseRef(Name = @dbname).SetSuspect(Value = 1) 
 
    declare @dropCmd nvarchar(max) 
 
    select @dropCmd = 'drop database ' + quotename(@dbname) 
    exec (@dropCmd) 
    raiserror(15458,-1,-1) 
 
    return(0)   -- sp_dbremove 

HostForLIFE.eu SQL 2016 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



SQL Server 2016 Hosting - HostForLIFE.eu :: How to Calculate or Find median in SQL Server?

clock June 16, 2016 21:20 by author Peter

Today, with this post we explain that how to calculate median in SQL Server or function to find median in SQL Server. Before we calculate/find median in sql server first we understand the what is the median and formula to calculate the median in sql server.

Median means denoting or relating to a value or quality lying at the midpoint of a frequency distribution of observed values or quantities, such that there is an equal probability or falling or below it. To calculate or Find median grou by in SQL Server click here Calculate median group by in SQL Server. For ex: supposed to find the median of bellows values like:
{1,2,3,4,5} then the median is equal 3
{1,2,5,10} then the median is equal 3.5
{1,5,8,7} then median is equal 6

So how to calculate median in SQL Server query, below is the query to find the median

Query:
SELECT CONVERT(FLOAT,
(
(SELECT MAX(Score) FROM
(SELECT TOP 50 PERCENT Score FROM Demo ORDER BY Score ASC) AS BottomHalf))
+ CONVERT(FLOAT,
(SELECT MIN(Score) FROM
(SELECT TOP 50 PERCENT Score FROM Demo ORDER BY Score DESC) AS TopHalf)
) / 2) AS Median

HostForLIFE.eu SQL 2016 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



SQL Server 2016 Hosting - HostForLIFE.eu :: How to Calculate or Find median in SQL Server?

clock June 16, 2016 21:20 by author Peter

Today, with this post we explain that how to calculate median in SQL Server or function to find median in SQL Server. Before we calculate/find median in sql server first we understand the what is the median and formula to calculate the median in sql server.

Median means denoting or relating to a value or quality lying at the midpoint of a frequency distribution of observed values or quantities, such that there is an equal probability or falling or below it. To calculate or Find median grou by in SQL Server click here Calculate median group by in SQL Server. For ex: supposed to find the median of bellows values like:
{1,2,3,4,5} then the median is equal 3
{1,2,5,10} then the median is equal 3.5
{1,5,8,7} then median is equal 6

So how to calculate median in SQL Server query, below is the query to find the median

Query:
SELECT CONVERT(FLOAT,
(
(SELECT MAX(Score) FROM
(SELECT TOP 50 PERCENT Score FROM Demo ORDER BY Score ASC) AS BottomHalf))
+ CONVERT(FLOAT,
(SELECT MIN(Score) FROM
(SELECT TOP 50 PERCENT Score FROM Demo ORDER BY Score DESC) AS TopHalf)
) / 2) AS Median

HostForLIFE.eu SQL 2016 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in