Skip to main content
29 votes
Accepted

How to get count for different columns on same table

It's easiest with SUM() and a CASE statement: select CompanyName, sum(case when StatusID=1 then 1 else 0 end) as TotalOpenClaims, sum(case when StatusID=2 then 1 else 0 end) as TotalClosedClaims, ...
Philᵀᴹ's user avatar
  • 31.8k
23 votes

Which is faster, SUM(CASE) or CTE PIVOT?

Are there examples where PIVOT is slower? This is unlikely in simple cases. As Itzik Ben-Gan notes in his SQL Server Pro article, Pivoting Data when looking at the plan for a PIVOT query (emphasis ...
Paul White's user avatar
  • 86.9k
18 votes

How to get count for different columns on same table

This is a typical pivot transformation, and conditional aggregation, as suggested by Phil, is the good old way of implementing it. There is also a more modern syntax of achieving the same result, ...
Andriy M's user avatar
  • 23.1k
16 votes

How do I generate a pivoted CROSS JOIN where the resulting table definition is unknown?

Simple case, static SQL The non-dynamic solution with crosstab() for the simple case: SELECT * FROM crosstab( 'SELECT b.x, f.name, f.x * b.x AS prod FROM foo f, bar b ORDER BY 1, 2' ) AS ...
Erwin Brandstetter's user avatar
15 votes
Accepted

How to Pivot in T-SQL

To your data set, I added a row number (ROW_NUMBER), and this field is divided by 5 (you wanted 5 columns in the output) and hold the rest and the hole number of this division in fields inRows , ...
Sabin B's user avatar
  • 4,466
14 votes
Accepted

When converting dynamic SQL (pivot query) to xml output, why is the first digit of the date converted to unicode?

Attribute names in XML are not allowed to start with a number, see NameStartChar. You have to come up with alternative names for your attributes and encode that in a separate @cols variable ...
Mikael Eriksson's user avatar
14 votes
Accepted

How to pivot on multiple columns in SQL Server?

Here is one way of getting the result set you want without doing the multiple joins. It takes a little more setup and uses two pivot operations instead of one, but avoids the multiple joins. I ...
Jonathan Fite's user avatar
13 votes

Which is faster, SUM(CASE) or CTE PIVOT?

Repeating the tests from Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - By Jeff Moden, 2010/08/06 (first published: 2008/08/19) on rextester Unfortunately I can not access statistics for ...
SqlZim's user avatar
  • 2,420
12 votes

How do I generate a pivoted CROSS JOIN where the resulting table definition is unknown?

What's the best we can do in PostgreSQL without a "column definition list" to generate that kind of presentation? If you frame this as a presentation problem, you might consider a post-query ...
Daniel Vérité's user avatar
12 votes

How to pivot rows into columns MySQL

GROUP BY and using MAX or SUM is the most used standard pivot way. SELECT results.sims_id , results.subject , MAX(CASE WHEN results.progress_check = "C1" THEN results.result END) "C1" , MAX(...
Raymond Nijland's user avatar
12 votes
Accepted

Is it possible to PIVOT on a LIKE statement

SUM(CASE For a limited number of Names you can use a SUM(CASE solution in this way: SELECT 'Database status' as [DB Status], SUM(CASE WHEN Name LIKE 'Test%' THEN 1 ELSE 0 END) As Test, ...
McNets's user avatar
  • 23.8k
11 votes
Accepted

How to create recurrent weekdays as columns in a pivot?

The most complex part of this is just building the calendar in that format. Pivoting and surrounding it with HTML is pretty easy. First, let's start with this, your employee table with leave dates. ...
Aaron Bertrand's user avatar
10 votes
Accepted

Query monthly having group_concat and group by need help

Terminology and Methodology This kind of transformation – rows to columns – is called pivoting. It is typical to pivot data simultaneously with their aggregation, as seems to be a requirement in your ...
Andriy M's user avatar
  • 23.1k
10 votes

How to pivot on multiple columns in SQL Server?

Given: DECLARE @T table ( ID integer NOT NULL PRIMARY KEY, hProp integer NOT NULL, iDayOfMonth integer NOT NULL, dblTargetPercent decimal(6,4) NOT NULL ); INSERT @T (ID, hProp, ...
Paul White's user avatar
  • 86.9k
9 votes
Accepted

group a multiple union statement

What you are trying to do looks very much like a pivot operation. You could probably achieve the result you are looking for without a derived table, using conditional aggregation: SELECT ...
Andriy M's user avatar
  • 23.1k
8 votes
Accepted

How to pivot rows into columns MySQL

This is one way to pivot using standard SQL (and the part of the standard that MySQL implements). That means it not only works in MySQL, but also in most SQL databases: SELECT r0.sims_id, r0....
joanolo's user avatar
  • 13.5k
8 votes

Name for table with metric_name and metric_value columns

Unpivot Table Being the product of a transformation, your desired form here is called an "Unpivot table". The form you're starting from here is either normalized data, or the result of a ...
Evan Carroll's user avatar
  • 63.9k
8 votes

Is it possible to PIVOT on a LIKE statement

I think it's important to strictly separate the two tasks you're trying to perform in one step here. Classification Transformation For classifying the data, my instinct here is to recommend a lookup ...
Peter Vandivier's user avatar
7 votes
Accepted

Rotate table for year-over-year comparison

Yes, more concise ways of pivoting exist for your scenario. Option 1 For instance, you could use the PIVOT operator: SELECT * FROM ( SELECT road_id, insp_year, condition ...
Andriy M's user avatar
  • 23.1k
7 votes
Accepted

Pivot with rollup in sql server

This can be done with PIVOT and it can be done dynamically, but before you jump in trying to do this dynamically, you should try to get the result you want using a static or hard-coded version of the ...
Taryn's user avatar
  • 9,696
6 votes
Accepted

SELECT multiple values from one table having matching record in another table in one row

Actually, since there can be n number of values for a single record of table first. the number of columns to return is not exactly arbitrary. There is a maximum of columns, and this has a clean ...
Erwin Brandstetter's user avatar
6 votes
Accepted

How to Pivot Multiple Columns

Instead of the PIVOT you can simply use the CASE WHEN .... By using GROUP BY then use MAX(CASE will return your expected result: Sample execution with the given sample data: DECLARE @...
Arulkumar's user avatar
  • 1,127
6 votes

When converting dynamic SQL (pivot query) to xml output, why is the first digit of the date converted to unicode?

The first character isn't Unicode, per se. I mean, technically all characters in XML within SQL Server are encoded as UTF-16 Little Endian, so in that sense they are all Unicode. But, what you are ...
Solomon Rutzky's user avatar
6 votes

Which is faster, SUM(CASE) or CTE PIVOT?

Just a note to correct a false assumption: There are three, not two, main ways to write a pivot. The third is using a driving table and several joins (with either LEFT JOIN or OUTER/CROSS APPLY): ...
ypercubeᵀᴹ's user avatar
6 votes
Accepted

Tips on reshaping data, pivot-like?

You can pivot your data using crosstab, but as usual it requires a well-known column's name. First you should install tablefunc module. CREATE EXTENSION tablefunc; Then you can call a crosstab with ...
McNets's user avatar
  • 23.8k
6 votes

Merge multiple rows into fewest number of rows of distinct values

Here are a couple ways you might approach the task by assigning an arbitrary row number to each of the non-NULL values for each column (avoiding extraneous sorts since the problem statement does not ...
Geoff Patterson's user avatar
6 votes

Merge rows values if the FK is same

You can use STRING_AGG to solve this problem (SQL Server 2017): SELECT FK, STRING_AGG(name, ', ') AS NAME FROM dbo.NotProvidedTableName GROUP BY FK If you are on an older version, you can use the FOR ...
Peter's user avatar
  • 2,372
5 votes

Is it possible to create a dynamic join?

Basically it's a crosstab query: PostgreSQL Crosstab Query The dynamic result type is a problem, though. ... is it possible to create a dynamic query which will output the right thing regardless ...
Erwin Brandstetter's user avatar
5 votes
Accepted

How can I pivot a view into a join so I get multiple query rows as columns in a single row?

Using the PIVOT clause, you can achieve the result like this: SELECT Vehicle_ID, Doors, [Engine Size], [Tire Size], [Color] FROM dbo.YourView PIVOT ( MAX(Value) FOR Property IN (...
Andriy M's user avatar
  • 23.1k

Only top scored, non community-wiki answers of a minimum length are eligible