Grafana: how to overwrite values in one table with value mapping retrieved from another table - grafana

I have two tables as below. 1st table contain descriptions of all statuses. How to overwrite column status_id on right table with name from left table based on id?

Option 1: fixed list of mappings
When the status are fixed and a low number, I would recommend to use value mapping.
Make sure not to apply it to the whole table, but instead to use an override for the field status_id in your table.
Option 2: variable list of mappings
In case the status change or new ones are added, I would suggest a workaround as follows (since I don't use PostgreSQL, I show SQL statements from Google BigQuery standard SQL, please adjust for your usecase):
Create a query variable: query the table with the mappings (the description of the status) and by using concatenation, create the WHEN ... THEN ... part of a case statement. Example:
SELECT CONCAT('WHEN "', id, '" THEN "', name, '" ')
FROM ID_TABLE
This will give you rows like this: WHEN "1" THEN "OK". Then you have to concat/aggregate those rows to a single string.
Then use the variable in the query for your final table like in this example:
SELECT
CASE status_id
${QUERY_VARIABLE}
ELSE "UNKNOWN STATUS"
END AS status_id,
...
FROM YOUR_DATA_TABLE

Related

IDENTITY_INSERT ON not working - SQL Server 2008 R2

I am having problems with my query.
Basically, what I am trying to do is empty out a table and copy the records from the same table in another database.
I did use the SET IDENTITY_INSERT code to make sure that the identity column is turned off before I perform my insert. But somehow, it still throws me the error message:
Msg 8101, Level 16, State 1, Line 3
An explicit value for the identity column in table 'dbo.UI_PAGE' can only be specified when a column list is used and IDENTITY_INSERT is ON.
Below is my query:
DELETE FROM [DB1].[dbo].[MY_TABLE]
SET IDENTITY_INSERT [DB1].[dbo].[MY_TABLE] ON
INSERT INTO [DB1].[dbo].[MY_TABLE]
SELECT *
FROM [DB2].[dbo].[MY_TABLE]
SET IDENTITY_INSERT [DB1].[dbo].[MY_TABLE] OFF
Can someone point me as to which step I am doing wrong?
Thanks a lot!
You have to specify all the column names when inserting with IDENTITY INSERT ON when using INSERT INTO
INSERT INTO [DB1].[dbo].[MY_TABLE](TabelID,Field1,Field2,Field3...)
SELECT * FROM [DB2].[dbo].[MY_TABLE]
In case you did not know there is a nifty little trick in ssms. If select a table and expand its' nodes you ctrl-c copy on the Columns node and that will place a comma-delimited list of the field names on your clipboards text buffer.
Addition to the first answer given by Ross Bush,
If your table has many columns then to get those columns name by using this command.
SELECT column_name + ','
FROM information_schema.columns
WHERE table_name = 'TableName'
for xml path('')
(after removing the last comma(',')) Just copy past columns name.

Create function/variable/parameter in pgAdmin with specific values

Not sure whether this is possible and what's the best way to do it, but I have a list of values (say it is 'ACBC', 'ADFC', 'AGGD' etc.) which grows over time. I want to use these values in pgADmin as a sort of variable/parameter for SQL statements; e.g:
Codes = {'ACBC', 'ADFC', 'AGGD'}
SQL: Statement => SELECT * FROM xxx WHERE SUBSTRING IN (Codes)
Is that somehow realizable, either with a variable, parameter, function or anyhing else?
I can think of the following options:
1) Create separate table
create table qry_params(prm_value varchar);
insert into qry_params values
('xxx'),
('yyy'),
('zzz');
select * from xxx where substring in (select prm_value from qry_params)
Whenever you have new parameter, you just need to add it to the table.
2) CTE at the top of query
Use query like:
with params (prm_value) as (select values ('xxx'), ('yyy'), ('zzz'))
select * from xxx where substring in (select prm_value from qry_params)
Whenever you have new parameter, you just need to add it to the CTE.

How to update an XML column in DB2 with XMLQuery?

I want to update an XML column in DB2 with dynamic values or you can say with values that I'll pick from another table and insert them in the xml column.
I know how to insert a node along with its value that we provide by
hard coding it, e.g.
<data>some_value</data>
I want to do it in the following way:
UPDATE my_table SET my_table_column = XMLQuery(..... <data>???</data>)
WHERE my_table_id = other_table_id;
Where I place ??? I need a kind of select statement here which will come up with actual value for the node.

pqxx column names in multi table request

This question is specific to libpqxx.
Given an SQL statement like the following:
string s = "SELECT a.foo, b.bar FROM tableOne a, tableTwo b WHERE a.X=b.X"
and sending it to a pqxx transaction:
trans.exec(s.c_str(), s.c_str());
What names will the columns have in the result field?
In other words, assuming 1 row is selected:
pqxx::result::const_iterator row = result.begin();
int foo = row->at(FOO_COLUMN).as<int>();
int bar = row->at(BAR_COLUMN).as<int>();
What values should FOO_COLUMN and BAR_COLUMN have? Would they be "a.foo" and "b.bar", respectively?
If the SQL statement renamed the variables using the "as" keyword, then I suppose the column name would be whatever "as" set it to, is that right?
Normally I would try an SQL and print the column values, but as I am developing both the software and the database itself, doing that test is not very easy right now.
Thanks!
The names are going to be foo and bar. If they were aliases in the query, then the aliases would be returned, the original names being lost.
Column names in results never include table names.
If they were named tablename.colname, it would be ambiguous anyway because SELECT 1 as "foo.colname" is valid and produces a column foo.colname despite the fact there is no foo table.
The way to identify the table from which a column originates, when it applies, is to call pqxx::result::column_table(column_number) which returns the oid of the table. The table's name is not available directly but could be queried in pg_class with the oid.
Also note that column names don't have to be unique within a resultset. SELECT 1 AS a, 2 AS a is valid and produces two columns with exactly the same name.

T-SQL Parse text in select statement

I am currently working on a project to import data from one table to another. I am trying to parse a field that contains a FULLNAME into its parts LAST,FIRST,MI. The names are all in the format of "LAST,FIRST MI" I have written a stored procedure that correctly parses and returns the results as neccessary but I am unsure as to how to encorporate the stored procedure into a single select statement. For instance, current I have:
SELECT FULLNAME From UserInfo
and what I would like to have is something like this:
SELECT Last, First, MI from UserInfo
Currently my stored procedure takes the form of ParseName(FULLNAME, Last as OUTPUT, First as OUTPUT, MI as OUTPUT). How can I call this procedure and have the output variables split into 3 different columns?
Replace your stored procedure with table valued function. You can then apply this function to all the rows.
Below is an example - just put your logic for parsing the name
create FUNCTION dbo.f_parseName(#inFullName varchar(255))
RETURNS
#tbl TABLE (lastName varchar(255), firstName varchar(255), middleName varchar(255))
as
BEGIN
-- put your logic here
insert into #tbl(lastName,firstName,middleName)
select substring(#inFullName,0,10),substring(#inFullName,11,10), substring(#inFullName,21,10)
return
end
apply the function
-- sample data
declare #fullNames table (fullName varchar(255))
insert into #fullNames (fullName) values
('111111111122222222223333333333')
,('AAAAAAAAAABBBBBBBBBBCCCCCCCCCC')
select
fn.fullName
,pn.lastName
,pn.firstName
,pn.middleName
from
#fullNames fn
cross apply dbo.f_parseName(fn.fullName) pn
You could put the results of your stored procedure in a (temporary) table, like this (I added the FULLNAME column to provide a join condition, you would have to adapt your stored procedure to do that):
CREATE TABLE #temp (
FULLNAME NVARCHAR(..)
,Last NVARCHAR(..)
,First NVARCHAR(..)
,MI NVARCHAR(..)
);
INSERT INTO #temp (Last, First, MI)
EXECUTE MySproc;
If you want to be able to execute SELECT Last, First, MI from UserInfo structurally, you'd have to first add three columns to UserInfo for your name information, and then insert the parsed data that you got from your stored procedure.
EDIT
You mention that you use a SELECT ... INTO ... to put the data in a new table. I'm guessing that the new table does not have the FULLNAME column, and then you would be better off using a table valued function (as this answer suggests). If you keep the FULLNAME column however, you can use that to join the temp table with your new table to update the new table as follows:
UPDATE NUI
SET NUI.Last = T.Last, NUI.First = T.First, NUI.MI = T.MI
FROM NewUserInfo AS NUI
INNER JOIN #temp AS T ON NUI.FULLNAME = T.FULLNAME;
You could use this UPDATE method also with another join condition if you do not have the FULLNAME column in your new table, but make sure you run a good test beforehand to check if the join holds.
Hope this helps, good luck!
You could add computed columns to table like this:
alter table UserInfo
add firstName as SUBSTRING(fullName, CHARINDEX(',',fullName,0)+2, LEN(fullName)-CHARINDEX(',',fullName,0)-CHARINDEX(' ', REVERSE(fullName),0)-1)
,lastName as SUBSTRING(fullName, 0, CHARINDEX(',',fullName,0))
,middleInitital as REVERSE(SUBSTRING(REVERSE(fullName),0,CHARINDEX(' ', REVERSE(fullName),0)))
But the best solution would be to do the other way around. Normalize the data with real columns for firstName, lastName and middleInitial and do a computed column for the fullName.
The expressions in the code above may need a little more work, as I am sure they can be written more effectivly. I only made them work to show the idea.
After creating the computed columns you may do this:
select firstName
,lastName
,middleInitital
from UserInfo