Solving tech problems

How to delete duplicated records in MS SQL Server?

Databases, Programming

First, create one demo table Let’s create one demo table first. It will be called Person and will hold some fictive person data. Now, fill the data Insert some fictive person data and do some duplicated records that have the same values for fields  firstname, lastname and email. Now the magic Use this subquery trick to extract duplicate records and then delete them. Notice the use of PARTITTION and WITH Transact-SQL keywords. All records that have RowNumber > 1 are deleted.

Using SQL Server APPLY command in queries

Databases

APPLY clause in Transact-SQL is interesting because it can be user in the following scenario: For example, you might create a query that returns a list of payments (in this case last 2 payment amounts and dates) for each subscriber inside your SaaS product. You get something like this 958 Usain Jordan 2014-06-01 299.00 958 Usain Jordan 2014-07-18 458.00 110 Seagal KungFu 2014-01-12 15.16 110 Seagal KungFu 2014-03-06 17.45

Using SQL Server PIVOT feature to transform rows into columns

Databases, Programming

PIVOT queries in SQL Server are useful when we need to transform data from row-level to column-level. Example: Imagine having the table named Invoice (payments per month) – for simplicity let’s say that we have PaidDate and Amount. What we wanted now is to get total money collected from the beginning of the year 2014, and in order to do this we can use this PIVOT query: And we finally get

How to get list of sequential dates in MS SQL Transact SQL and cursors alternative

Databases

Let’s imagine that we have table where we store some service prices and that this price can vary regarding period of the year. You would then have something like this in your table: $50 from January 1st to May 31th $70 from June 1st to October 31th $60 from November 1st to December 31th What we want is to get all daily prices for given date region. So, if we give range from May 15th to 15th June we want to get this: May 15th $50 May 16th $50 May…read more

Top 10 query optimizing tips for MS SQL Server

Databases

During my 15 years of experience and working on various projects that involved using MS SQL Server in combination with C# programming language, and also gathering knowledge from different conferences, especially from the last one that occured today at SQL Saturday by ApexSQL where Miloš Radivojević showed some tips, I tried to summarize this knowledge in a small list of recommendations that you should be aware of when writing the Transact SQL queries… 1. Using local defined variables When possible always try to use direct values instead of variables (this…read more