SQL Server 2012 Filtering Results Based on One Table and Appending Info - sql

I've been trying to search for a similar query on stackoverflow to modify to get what I need but I can't seem to get it right. I hope someone here can help.
I have two tables located in two different databases. Both databases are configured on the same server. Table 1 called 'DiscreteLive' and located in Database 'Runtime'. Table 2 is called 'v_DiscreteHistory' and located in Database 'WWALMDB'.
They have the following fields
DiscreteLive
Tagname (type String)
Value (type Integer --> can only ever be 1 or 0)
'v_DiscreteHistory'
Tagname (type String)
Value (type String --> can only ever be true of false)
EventStamp (type datetime)
Description (type String)
The 'DiscreteLive' table can only ever have one unique tagname line. An external software will overwrite to each tagname's corresponding Value field. It's basically showing the live values of the system. Example shown below. For example, you would never find Device1.Commfail twice in this table.
Device1.Commfail
Device1.Auto
Device1.Man
Device2.Commfail
Device2.Auto
Device2.Man
Device3.Commfail
Device3.Auto
Device3.Man
Device4.commfail
Device4.Auto
Device4.Man
Device5.Commfail
Device5.Auto
Device5.Man
etc.
The 'v_DiscreteHistory' table is the history of the specific tag. There can be multiple entries of the same tag along with its Description and EventStamp (Time the even happened).
What I'm trying to do is to filter out the 'DiscreteLive' table to show only the tag values where the tagname is a %.CommFail and the Value is 1. Then I would like to take the result of that initial query and attach the latest EventStamp and Description for those tags in the initial query from 'v_DiscreteHistory'.
Not sure if this can be done. Let me know if you need more clarification.

SQL Server: This might be what you are looking for
SELECT
D.TagName
,D.Value
,V.Tagname
,V.Value,V.EventStamp
,V.Description
,MAX(V.EventStamp) AS 'LatestDate'
FROM
SERVER.Runtime.dbo.DiscreteHistory D
INNER JOIN
SERVER.WWALMDB.dbo.v_DiscreteHistory V
ON
D.Tagname = V.Tagname
WHERE
D.Value = 1
AND
V.Value LIKE '%.CommFail'
GROUP BY
D.TagName
,D.Value
,V.Tagname
,V.Value,V.EventStamp
,V.Description

Related

Multiple entries in crystal reportviewer after adding a SQL expression field

I am using Visual Studio 2017 and I installed the latest crystal reportviewer (22)
What I want is to click a button and create a report from the customer that is selected in the datagridview and the addresses that are shown in the second datagridview.
I managed to do all that but the problem is that a few fields contain numbers which need to be converted to text. An SQL query I would use to do this would be like:
SELECT c.customer_nr, c.status, s.rename FROM CUSTOMERS c INNER JOIN SETUP s on s.id = c.status WHERE s.afk = 'STA'
In my SETUP database I have the columns ID,AFK and RENAME so if the status would be 1 it would convert to text: "ACTIVE", if status = 2 it would convert to "INACTIVE" for example.
I could do something with a formula field like this:
IF ({c.status} = 1) THEN "ACTIVE" ELSE
IF ({c.status}) = 2 THEN "INACTIVE"
but that is not good because i could add another status or change the name in the database etc.
So then I tried with an SQL expression field and I put something like this:
(
SELECT "SETUP"."RENAME" FROM SETUP
WHERE "SETUP"."AFK" = 'STA' AND "SETUP"."ID" = "CUSTOMERS"."STATUS"
)
There must be something wrong because I get the correct conversion but there is only one address in the database but I get 7 pages all with the same address. There should only be one address like I get when I remove the SQL expression field. Where does it go wrong?
* EDIT *
I found the problem. When I create a new database that contains only unique id's then it works. In my original database I have multiple times the id's 1,2,3,4,5 but with different abbreviations in column AFK. Somehow the query looks for the id value and every time it finds this id no matter the AFK value it generates an entry for the address value.
Maybe in the future I will find out how this exactly works for now I have a workaround.
Create a new table for example CrRepSta and add the following entries:
ID,AFK,RENAME
1,STA,Active
2,STA,Inactive
etc
The new query:
(
SELECT "CrRepSta"."RENAME" FROM CrRepSta
WHERE "CrRepSta"."AFK" = 'STA' AND "CrRepSta"."ID" = "CUSTOMERS"."STATUS"
)
And by the way the statement "CrRepSta"."AFK" = 'STA' is not really needed.

MS Access-Return Record Below Current Record

I am very new to Access, and what I am trying to do seems like it should be very simple, but I can't seem to get it.
I am a structural engineer by trade and am making a database to design buildings.
My Diaphragm Analysis Table includes the fields "Floor_Name", "Story_Number", "Wall_Left", and "Wall_Right". I want to write a new query that looks in another query called "Shear_Wall_incremental_Deflection" and pulls information from it based on input from Diaphragm Analysis. I want to take the value in "Wall_Right" (SW01), find the corresponding value in "Shear_Wall_incremental_Deflection", and report the "Elastic_Deflection" corresponding to the "Story_Below" instead of the "Story_Number" in the Diaphragm Analysis Table. In the case where "Story_Number" = 1, "Story_Below" will be 0 and I want the output to be 0.
Same procedure for "Wall_Left", but I'm just taking it one step at a time.
It seems that I need to use a "DLookup" in the expression builder with TWO criteria, one that Wall_Right = Shear_Wall and one that Story_Number = Story_Below, but when I try this I just get errors.
"Shear_Wall_incremental_Deflection" includes shearwalls for all three stories, i.e. it starts at SW01 and goes through SWW for Story Number 3 and then starts again at SW01 for Story Number 2, and so on until Story Number 1. I only show a part of the query results in the image, but rest assured, there are "Elastic_Deflection" values for story numbers below 3.
Here is my attempt in the Expression Builder:
Right_Defl_in: IIf(IsNull([Diaphragm_Analysis]![Wall_Right]),0,DLookUp("[Elastic_Deflection_in]","[Shear_Wall_incremental_Deflection]","[Shear_Wall_incremental_Deflection]![Story_Below]=" & [Diaphragm_Analysis]![Story_Number]))
I know my join from Diaphragm_Analysis "Wall_Left" and "Wall_Right" must include all records from Diaphragm_Analysis and only those from "Shear_Wall_incremental_Deflection"![Shear_Walls] where the joined fields are equal, but that's about all I know.
Please let me know if I need to include more information or send out the database file.
Thanks for your help.
Diaphragm Analysis (Input Table)
Shear_Wall_incremental_Deflection (Partial Image of Query)
I think what you are missing is that you can and should join to Diaphragm_Analysis twice, first time to get the Story_Below value and second to use it to get the corresponding Elastic_Deflection value.
To handle the special case where Story_Below is zero, I would write a separate query (only requires one join this time) and 'OR together' the two queries using the UNION set operation (note the following SQL is untested):
SELECT swid.Floor_Name,
swid.Story_Number,
swid.Wall_Left,
da2.Elastic_Deflection AS Story_Below_Elastic_Deflection
FROM ( Shear_Wall_incremental_Deflection swid
INNER JOIN Diaphragm_Analysis da1
ON da1.ShearWall = swid.Wall_Left )
INNER JOIN Diaphragm_Analysis da2
ON da2.ShearWall = swid.Wall_Left
AND da2.Story_Number = da1.Story_Below
UNION
SELECT swid.Floor_Name,
swid.Story_Number,
swid.Wall_Left,
0 AS Story_Below_Elastic_Deflection
FROM Shear_Wall_incremental_Deflection swid
INNER JOIN Diaphragm_Analysis da1
ON da1.ShearWall = swid.Wall_Left
WHERE da1.Story_Below = 0;
I've assumed that there is no data where Story_Number is zero.

How to Take two SQL queries of a column of substrings to search database using the appended result of the other

I have two select statements that both contain a column of substrings that derived from a database table. They are substrings derived from a varchar that should be an XML, but were saved as varcars because they could be not well-formed and potentially invalid.
I am trying to take the table that results in the 1st query, a list of 50 Varchars, and search the database using the 2nd query. I could get from 0 to n SQLRelatesMessageID sets from each SQLmessageID if I use each row in the first query and append a string to get the node ("z4480" is an example here).
I have tried a cursor implementation but the performance detered me from finishing it. Join doesn't work if you try giving the substring column with an as alias. What steps should I do to get the overall list of SQLRelatesMessageIDs. My goal is to get all MessageLogId (3 in picture) given a NCPDPID.
I am using SQL Server Manager 2012.
--1--Recieves a list based on a given NCPDPID node Value
select substring(m.message, charindex('<MessageID>', m.message)+11, charindex('</MessageID>', m.message)-charindex('<MessageID>', m.message)-11) as
SQLmessageID from messagelog m where message like '%<NCPDPID>'+'1234567'+'</NCPDPID>%'
--2--Selects messageID from top select and searches RelatesToMessageID node
select substring(r.message, charindex('<RelatesToMessageID>', r.message)+20, charindex('</RelatesToMessageID>', r.message)-charindex('<RelatesToMessageID>', r.message)-20) as SQLRelatesMessageID, * from messagelog r
where message like ('%<RelatesToMessageID>'+'z4480'+'</RelatesToMessageID>%')
This works for this answer.
---main
SELECT * FROM
(
select substring(m.message, charindex('<MessageID>', m.message)+11, charindex('</MessageID>', m.message)-charindex('<MessageID>', m.message)-11) as SQLmessageID from messagelog m
where message like '%<NCPDPID>1234567</NCPDPID>%' and dateTime > '3/01/2016'
) a JOIN
(
select
substring(r.message, charindex('<RelatesToMessageID>', r.message)+20, charindex('</RelatesToMessageID>', r.message)-charindex('<RelatesToMessageID>', r.message)-20) as SQLRelatesMessageID,
message,
messagelogid from messagelog r
where
dateTime > '3/01/2016' AND
message LIKE ('%<RelatesToMessageID>%</RelatesToMessageID>%')
) b ON b.SQLRelatesMessageID = a.SQLmessageID

Filling 2 records inside of a rowset

I am trying to find out how to fill two seperate records in one rowset to be published to integration broker. I am filling both rowsets seperatly (RS1 for the Level 1 of record Names and RS for the Level 0 record of Person)
&RS1 = CreateRowset(Record.NAMES);
&RS1.Fill("Where emplid=:1 and name_type=:2", &emplid, &nameType);
&RS = CreateRowset(Record.PERSON, &RS1);
&RS.Fill("Where emplid=:1", &emplid);
I have also tried to use this after the above code and the NAMES record didnt show up into the rowset
&RS1.CopyTo(&RS, Record.NAMES, Record.PERSON);
The problem is that when I look at &RS after this runs, the Names record in &RS does not contain any of the name information from &RS1, but the person record is populated. Could anybody help me on how to get this name record in &RS populated with the data from &RS1?
The issue with your code is that &RS1 is really just used to determine the structure of &RS. The actual instantiated rowset is not part of &RS. In the code below note where I get the NAMES rowset for a specific row and assign it to &RS1, then I fill it.
Local Rowset &RS, &RS1;
&RS1 = CreateRowset(Record.NAMES);
&RS = CreateRowset(Record.PERSON, &RS1);
&RS.Fill("Where emplid=:1", &emplid);
&RS1 = &RS(1).GetRowset(Scroll.NAMES);
&RS1.Fill("Where emplid=:1 and name_type=:2", &emplid, &nameType);

Need to pull only last date in table that stores change dates SQL / ODBC

Hope somebody can help me with this. I'm trying to pull a list of forthcoming titles (I work in publishing) via ODBC/ms query. I want (amongst other things) to show their internal status (approved, prepress etc.). The database stores the change dates for the status'. I seem to be getting one line per status per title. So if the title has changed status 6 times, I will get 6 lines. But I only want to show the latest status...
The date is in BL_PROJECT_TO_STATUS.STATUS_DATE (I've inserted a date criteria beneath, just to make it more visible).
How can this be done? I'm very new to ODBC and would appreciate it a lot.
SELECT DISTINCT
BL_PROJECT.EXP_PUB_DATE, BL_PROJECT.EAN, BL_PROJECT.TITEL,
MEDIATYPE.DESCRIPTION, BL_PROJECT_STATUS.DESCRIPTION
FROM
FIRMA1.BL_PROJECT BL_PROJECT, FIRMA1.BL_PROJECT_STATUS BL_PROJECT_STATUS,
FIRMA1.BL_PROJECT_TO_STATUS BL_PROJECT_TO_STATUS, FIRMA1.MEDIATYPE MEDIATYPE
WHERE
BL_PROJECT.PROJECT_ID = BL_PROJECT_TO_STATUS.PROJECT_ID AND
BL_PROJECT_TO_STATUS.STATUS_ID = BL_PROJECT_STATUS.CODE AND
BL_PROJECT.MEDIATYPE = MEDIATYPE.ID AND
((BL_PROJECT.PROJECT_TYPE = 2) AND
(BL_PROJECT.EXP_PUB_DATE Between SYSDATE AND (SYSDATE+90)) AND
(BL_PROJECT_TO_STATUS.STATUS_DATE = {ts '2013-11-20 00:00:00'}))
ORDER BY
BL_PROJECT.EXP_PUB_DATE, BL_PROJECT.EAN, BL_PROJECT.TITEL
Here is the general idea. You can adapt it with your table and field names.
select somefields
from sometables
join
(select something, max(datetimefield) maxdt
from table1
where whatever
group by something ) temp on table1.datetimefield = maxdt
etc