You can use the PIVOT function to perform this query. My answer will include both a Static and dynamic version because sometimes it is easier to understand it using a static version.
A Static Pivot is when you hard-code all of the values that you want to transform into columns.
-- first into into a #temp table the list of dates that you want to turn to ...
It's easiest with SUM() and a CASE statement:
sum(case when StatusID=1 then 1 else 0 end) as TotalOpenClaims,
sum(case when StatusID=2 then 1 else 0 end) as TotalClosedClaims,
sum(case when StatusID=3 then 1 else 0 end) as TotalReOpenedClaims,
sum(case when StatusID=4 then 1 else 0 end) as TotalPendingClaims
group by ...
There are a few ways that you can perform this data transformation. You have access to the PIVOT function then that will be the easiest, but if not then you can use an aggregate function and a CASE.
Aggregate /Case version:
max(case when optionid = 'A' then 1 else 0 end) OptionA,
max(case when optionid = 'B' then 1 else 0 end) OptionB,
This is a bit messy to get the final result because you have multiple SCHEMA_VER for each date. Before I demonstrate how to do this with dynamic SQL, I'll first show how to do it with static code to get the logic correct. In order to get the final result you can utilize both pivot and unpivot.
But first, I'd change your original query to use the following:
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 added):
Figure 3 shows the plan for the PIVOT query. As you can see, this plan is very similar to that of the standard solution—so much so that if you look at ...
This type of rotation of data from columns to rows is known as a PIVOT. MySQL does not have a pivot function but you can use an aggregate function with a CASE expression to get the result.
My first suggestion would be to determine if you have a calendar table or a table that contains all of the dates that you want to display. If not, then I would suggest ...
As others have said this is known as a PIVOT. There are several ways in which you can transform your data from rows into columns of data.
If you know the values ahead of time, then you can hard-code the values. Prior to the PIVOT function you would use an aggregate function with a CASE statement.
sum(case when [...
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 specifying column aliases for your dynamic pivot query.
SELECT @cols2 = STUFF((SELECT distinct ',' +
quotename(convert(char(10), [StayDate] , 120)...
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 , inColumns. Base on this, will do the pivot.
There is a special case when you divide by 5 and have rest = 0 ; for this I use case...
,RN / 5 + CASE WHEN RN % 5 = 0 ...
HOW TO DO THIS WITH T-SQL:
As requested this is an alternative to my previous answer that showed how to do it per-user with Excel. This answer shows how to do the same thing shared/centrally using T-SQL instead. I do not know how to do Cubes, MDX or the SSAS stuff for this, so maybe Benoit or someone who does know that can post its equivalent...
1. Add ...
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, which uses the PIVOT clause:
TotalOpenClaims = ,
TotalClosedClaims = ,
TotalReOpenedClaims = ,
TotalPendingClaims = [...
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 IO, Time or execution plans on rextester, but it has the unique benefit of being a common test environment that anyone here can tinker with and examine. I ...
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 ct (x int, "A" int, "B" int, "C" int, "D" int, "E" int
, "F" int, "G" int, "H" int, "I" int, "J" int);
I order resulting columns by foo....
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. leave_type didn't seem relevant to the problem at hand.
CREATE TABLE dbo.EmpLeave
For a limited number of Names you can use a SUM(CASE solution in this way:
'Database status' as [DB Status],
SUM(CASE WHEN Name LIKE 'Test%' THEN 1 ELSE 0 END) As Test,
SUM(CASE WHEN Name LIKE 'Prod%' THEN 1 ELSE 0 END) AS Prod,
SUM(CASE WHEN Name = 'Migrated' THEN 1 ELSE 0 END) AS Migrated,
SUM(CASE WHEN Name = '...
If you have a known number of columns, then you can use a static version similar to the other answer. But if you have an unknown number then you can use a prepared statement similar to this:
SET @sql = NULL;
'max(case when kode = ''',
''' then jum else 0 end) AS ',
) INTO @...
Prior to writing a dynamic SQL query, you should always write a version that is hard-coded so you can get the syntax correct. So the first thing you need to do is write a working PIVOT query for any of the TruckId values that you need.
Let's say you need TruckID = 3, your code for the PIVOT would be similar to the following:
select Name, ...
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 presentation feature.
Newer versions of psql (9.6) come with \crosstabview, showing a result in crosstab representation without SQL support (since SQL can't produce ...
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 case too. In SQL you can do both operations as a single logical step. Other SQL products even offer special syntactical extensions for pivoting, but there is a ...
This would be the equivalent in SQL Server syntax. Based on my reading of the Oracle docs, NULLIF and PIVOT appear to have the same format as their SQL Server kin. The challenge will be the pivot list which needs to be static unless you make the query dynamic as Itzik demonstrates but I have no idea if that can be translated to P/SQL
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:
COUNT(CASE WHEN orl_conditie_code = '001' THEN orl_conditie_code END) AS beschadigd,
COUNT(CASE WHEN orl_conditie_code = '002' THEN ...
As Martin Smith said, you need to pivot the data, whether with an explicit PIVOT as referenced or something like this (SQL Fiddle):
, SUM(Case When Month='Jan' Then Amount Else 0 End) MonthJan
, SUM(Case When Month='Apr' Then Amount Else 0 End) MonthApr
FROM Result GROUP BY SiteCode;
The most compact syntax I can find is:
FROM @T AS t
SELECT ISNULL(ISNULL(a, b), c)
SELECT ISNULL(ISNULL(b, c), a)
SELECT ISNULL(ISNULL(c, a), b)
Based on an idea from one of my old blog posts that describes how to use INTERSECT and EXCEPT to replace comparisons like a <> b OR (a ...
HOW TO DO THIS WITH EXCEL
Here's how I would do it in Excel...
1. Add SalaryRanges Excel Table
Insert a new worksheet, call it "Salary Ranges". In row one add the text headers "Min", "Max" and "Range" in that order (should be cells A1, A2, A3, respectively).
In cell B2 add the following formula:
In cell C2 add this ...
I'm old school, and find CASE easier to work out in my head than PIVOT. I'm sure bluefeet will show up shortly and put me to shame, but in the meantime you can play with this dynamic SQL query. Assuming your table stores DATE and not DATETIME (or even worse, VARCHAR):
CREATE TABLE dbo.a
To convert row to column you need to use CASE statement. And to get count for individual kode you need to use SUM function like this one:
SUM(CASE kode WHEN 'kode1' THEN jum ELSE 0 END) AS kode1
,SUM(CASE kode WHEN 'kode2' THEN jum ELSE 0 END) AS kode2
,SUM(jum) AS `Count`
GROUP BY Name
See this SQLFiddle
If you have the following table of data that you want to pivot:
CREATE TABLE yourtable (id int, name varchar2(1), value varchar(10));
INTO yourtable (id, name, value )
VALUES (1, 'A', '1500')
INTO yourtable (id, name, value )
VALUES (1, 'B', '4500')
INTO yourtable (id, name, value )
VALUES (2, 'C', '3.5')
You must Pivot data using GROUP BY with MAX aggregate and use CASE to filter by User_id.
CASE WHEN course_id = 1 THEN course_location END
) as Course_1
, MAX(CASE WHEN course_id = 2 THEN course_location END) as Course_2
, MAX(CASE WHEN course_id = 3 THEN course_location END) as Course_3
, MAX(CASE ...
This is a form of a "pivot", you should use that search term to find other options.
You can try something like this:
, sum(case when kode = 'kode1' then jum else 0 end) as 'kode1'
, sum(case when kode = 'kode2' then jum else 0 end) as 'kode2'
, sum(jum) as count
group by name;
(assuming your example view has an error for ...
This can be done using the PIVOT function, but since it sounds like you want to change the query based on the schemaId, then you will want to use dynamic SQL.
If you had a known number of values or knew the columns for a specific schemaID, then you could hard-coded the query. A static query would be: