tableau custom sql pivot - sql-server

I have a SQL Server data source that I cannot change the structure of.
I have started pivoting the data with CustomSQL query below, but I need to modify the query so that when iterations 3, 4 ,5 ...n data are added to the source in the future, it automatically includes it in the pivoted data. I don't want to have to keep updating the query. Any ideas?
KPI Name Iteration 1 Iteration 2
a 1 2
b 50 51
Select [KPI]
, 'Iteration1' as [Iteration]
, [Iteration1] as [Count]
From [MC_KPI]
Union ALL
Select [KPI]
, 'Iteration2' as [Iteration]
, [Iteration2] as [Count]
From [KPI]
Now I have this
KPI Name Iteration 1 Iteration 2
a 1 1
a 2 2
b 1 50
b 2 51

What you are doing is called "unpivot" in SQL Server. You can see the description here:
https://learn.microsoft.com/en-us/sql/t-sql/queries/from-using-pivot-and-unpivot?view=sql-server-2017
If you want to be able to add iterations without having to modify something in tableau, you can create a view in SQL that does unpivot and just do "select * from view" in tableau. This would give you the chance to change the view under the covers from tableau and have things continue to work (since the unpivot output is just a property bag and the columns are not really changing as you add properties into the output)

Related

SQLite Row_Num/ID

I have a SQLite database that I'm trying to use data from, basically there are multiple sensors writing to the database. And I need to join one row to the proceeding row to calculate the value difference for that time period. But the only catch is the ROWID field in the database can't be used to join on anymore since there are more sensors beginning to write to the database.
In SQL Server it would be easy to use Row_Number and partition by sensor. I found this topic: How to use ROW_NUMBER in sqlite and implemented the suggestion:
select id, value ,
(select count(*) from data b where a.id >= b.id and b.value='yes') as cnt
from data a where a.value='yes';
It works but is very slow. Is there anything simple I'm missing? I've tried to join on the time difference possibly, create a view. Just at wits end! Thanks for any ideas!
Here is sample data:
ROWID - SensorID - Time - Value
1 2 1-1-2015 245
2 3 1-1-2015 4456
3 1 1-1-2015 52
4 2 2-1-2015 325
5 1 2-1-2015 76
6 3 2-1-2015 5154
I just need to join row 6 with row 2 and row 3 with row 5 and so forth based on the sensorID.
The subquery can be sped up with an index with the correct structure.
In this case, the column with the equality comparison must come first, and the one with unequality, second:
CREATE INDEX xxx ON MyTable(SensorID, Time);

Inserting one table's complete column data to a particular column in another table in SQL Server

Inserting one table's complete column data to a particular column in another table in SQL SERVER
I have two tables i.e AuditCalendar, ScheduleAudit
Audit Calendar has two columns Taskid, TaskTypeId
Schedule Audit has two columns Scheduleid, Taskid
Audit Calendar looks like this
Taskid (Auto increment) TaskTypeId
-------------------------------------
1 1
2 2
3 3
4 1
5 1
But I want Taskid column data from Audit Calendar table based on TaskTypeId .Columns
After completion of query, the ScheduleAudit table should look like this
Scheuleid (AutoIncrement) Taskid
-------------------------------------
1 1
2 1
3 1
I have to run this query seems to look like a error
Subquery returns more than one value
Query is:
INSERT INTO ScheduleAudit(TaskId)
VALUES ((SELECT TaskId FROM AuditCalendar Where TaskTypeId = 1))
Please can you suggest how I can do this approach I am new to SQL Server but someone says that use cursors.... I am really confused last 1 week on words. And also search google but not get it now...Please can you give me any one valuable suggestions.
insert ... values is supposed to insert a single row. So what you have in the parentheses is supposed to produce a single row, or else it would fail.
There's no need to use insert ... values, when you can use insert ... select:
INSERT INTO ScheduleAudit(TaskId)
SELECT TaskId FROM AuditCalendar Where TaskTypeId=1
...however, that would produce
1 1
2 4
3 5
I'm not sure I understand the logic behind producing your example output.

How to (or Can I) select a random value from the Postgresql database excluding some particular records?

Is it possible to randomly select a record from the database excluding some records with particular status?
For eg,
For example, I have a table for storing employee details.
id employeename employeestatus
1 ab 1
2 cd 1
3 ef 2
4 gh 1
5 ij 1
What I want from the query is to fetch a single random record whose status is not 2. Is it possible to do so? The database I'm using is PostgreSQL 8.4.15.
TRY This
SELECT *
FROM employee
WHERE employeestatus != 2
ORDER BY RANDOM()
LIMIT 1
Try this other question on the same topic
Best way to select random rows PostgreSQL
It's tricker than you think (to do efficiently)

Different output when executing statement directly and from stored procedure?

Sql Server 2008 is behaving in a strange way. When I execute the stored procedure the out put is in a different order than when I execute the statements directly for the same parameters. I am not sure what I am doing wrong. Please help!!!
Here is a simple query structure and explain what it does.
Top 10 Query1
Union all
Top 10 Query2
Order by name
a. When u run it in a proc :
From Query 1 it fetches top 10 , then from query 2 it fetches top 10 and then finally it does the order
b. When you open the query :
From Query 1 it applies the order and then fetches top 10, and from Query 2 it also applies the order and then fetches top 10
This is strange that it's doing 2 different things with the same query.
Output from Procedure
Name Cost Price
A2 Bag Stickerss DO NOT STOCKTAKES 24
aaaaaa 5
aaaaaa 7.5
Output from Query
Name Cost Price
A2 Bag Stickerss DO NOT STOCKTAKES 24
A2 Bag Stickerss DO NOT STOCKTAKES 27
aaaaaa 5
aaaaaa 7.5
aaaaaa 9
TOP without ORDER BY is not deterministic.
It just means "Select any 10 records". So you are selecting an arbitrary set of 10 results from query 1 and an arbitrary set of 10 records from query 2 then ordering these 20 records by name.
Which TOP 10 you end up with depends on the plan chosen (which may well be different in the stored procedure) You would need to add an order by (on a set of columns with no ties) to each query to make it deterministic.
Your current query is like
SELECT TOP 10 *
FROM master..spt_values
UNION ALL
SELECT TOP 10 *
FROM master..spt_values
ORDER BY name
You see that SQL Server just adds a TOP iterator to both branches of the plan to limit the output of both queries then these feed into the Union and the sort by name happens after that. SQL Server chose a clustered index scan for this so the results will likely be the TOP 10 in clustered index order type,number,name (though this shouldn't be relied upon either, without a specified order by to indicate what the TOP refers to any set of 10 rows would be valid. It would be perfectly valid for it to use the advanced scanning feature here and give you an arbitrary 10 rows that it knows to be in cache as they have just been read by an other query's scan.)
To rewrite the query with TOP...ORDER BY specified for each element you could use CTEs as below.
;WITH Query1 AS
(
SELECT TOP 10 *
FROM master..spt_values
ORDER BY name,number,type
), Query2 AS
(
SELECT TOP 10 *
FROM master..spt_values
ORDER BY number,type,name
)
SELECT *
FROM Query1
UNION ALL
SELECT *
FROM Query2
ORDER BY name

How to create following table using MDX Scripting in Sql Server 2005?

I have the following table ,
Database Table:
BatchID BatchName Chemical Value
----------------------------------------------
BI-1 BN-1 CH-1 1
BI-2 BN-2 CH-2 2
----------------------------------------------
I need to display the following table.
BI-1 BI-2
BN-1 BN-2
-----------------------------------------
CH-1 1 null
------------------------------------------
CH-2 null 2
------------------------------------------
Here BI-1,BN-1 are two rows in a single columns i need to display chemical value as row of that.Could Please help me to solve this problem.
I tried it in Pivot table but i unable to get this.
So is there any chance in Reporting Server MDX.
First, you need to create a cube with Analysis Services (MDX only works against multidimensional data sources)
Then, assuming you have a cube "MYCUBE" with "Batch" and "Chemical" dimensions and a "Value" measure, the query would be something like this (of course, you could select just the members you need instead of all the members in the dimensions):
SELECT
{[Batch].members * [Measures].[Value]} on columns,
{[Chemical].members} on rows
FROM [MYCUBE]

Resources