does this LEFT OUTER JOIN statement look correct? - sql

I' not getting an error message but i seem to be only getting 5 results no matter what i choose, so this leaves me to beleive that there is something wrong with my SQL statement. I'm usint node.js tedious to connect to sql 2008 r2 database. Previous statements worked, but that was a simple select statement with the posting date where clause. I know there are spaces in my column names which is not good practice, but there is nothing i can do about that this because thedatabase is utilized by Navision. Normally there are no line breaks, i just did that to make it appear more orderly to you guys.
SELECT
TA.[Amount],
TA.[Posting Date],
TA.[Entry No_],
TA.[Document No_],
TB.[Salesperson Code]
FROM [ShowTex Belgie NV$G_L Entry] as TA
LEFT OUTER JOIN [ShowTex Belgie NV$Sales Invoice Header] as TB
ON TA.[Document No_]=TB.[No_]
WHERE TA.[Posting Date]>'05/01/2015'
AND TA.[Document Type]='2'
AND TA.[Gen_ Posting Type]='2'
Strangely Enough the SQL turns out not to be the issu. It is the conversion from JSON.stringify to JSON.parse. I was certain i had tested this successfully before. But perhaps i was negligent. Anyways My code looks like this. when i Console.log(retVal) the data still looks correct about 100 reccords as expected.
retVal = JSON.stringify({result:dataSet});
fn(retVal);
function fn(retVal){
var obj = JSON.parse(retVal);
for(var i = 0; i<Object.keys(obj.result[0]).length;i++){
console.log(obj.result[i]);
}
}
If i console.log(retVal) inside the fn function i still get my wall of text as expected. but within the FOR statement i only get the first 5 records. Hmm I bet I'm headbutting a rookie mistake at the moment. :/

Totally depends on what you want but here is a cheat sheet with venn diagrams. http://www.codeproject.com/KB/database/Visual_SQL_Joins/Visual_SQL_JOINS_orig.jpg so that it might be more logically to see what you are doing.

Wow, i found my problem. It's really embarrassing, the SQL was correct, i was counting the number of columns in my json file, this returned 5 each time. Sorry for Wasting people's time. Thank you so much for your feedback. It was helpfull in a sense that i was fixated on getting my sql statement wrong because I'm not good at those so your feedback was helpfull. It never occurred to me that I could still be running into rookie mistakes likes this.
i<Object.keys(obj.result[0]).length
needs to be
i<Object.keys(obj.result).length

Related

Unable to perform arithmetic operations in SQL

I hope you're well.
I've been toying with an SQL query recently but there's a column that is supposed to be the result of an arithmetic operation that does not seem to work for me. Here is the code I'm using:
select activecampaign.campaign_step,
count(activecampaign.email_name) as email_opened,
count(contracts.uuid) as contracts,
count(contracts.uuid)/count(activecampaign.email_name)*100 as cr_rate
from il.mktg_activecampaign_email_opens activecampaign
full outer join bl.leads leads
on leads.uuid = activecampaign.uuid
full outer join bl.contracts contracts
on leads.uuid = contracts.uuid
and contracts.conversion_channel = 'crm'
group by activecampaign.campaign_step
The first three select parameters are working just fine but the fourth one is not displaying anything I would expect. Here's a screenshot of the table it's producing:
My expectation here for the second row would be to see 3.86 but nothing of the sort is showing unfortunately.
Would anyone be able to point me in the right direction to solve this :) ?
Thank you very much for your time!

Join query giving empty result SQL

SQL learner here, trying to make a join, but it seems to not work.
I have the following 2 tables:
#device_combined_players
#final_results2
The goal is to have a new table replacing the player_store_id from #final_results with the pseudo_name from #device_combined_players.
I have tried with:
SELECT #final_results2.player_store_id,
#device_combined_players.pseudo_name, #final_results2.genre FROM #device_combined_players INNER JOIN #final_results2 ON #final_results2.player_store_id = #device_combined_players.store_id
but I can't make it work, my output is simply an empty table.
Could you guys, please, give me some light? Thank you!
My expected result would be: as #final_results2 (image 2), but replacing player_store_id column by pseudo_name from #device_combined_players table.
EDIT: a screenshot with more details:
https://i.stack.imgur.com/lSyLb.png
And, I am answering myself, since I had 2 different issues here. Both are rookie mistakes, but I will leave them here so it helps somebody else in the future:
Take a look at the data type of your columns. They can cause conflicts if they are not the same as the columns you are referencing in a JOIN.
Check if your data doesn't have spaces. You can use TRIM and LEN to help you out answering this.
I sorted my problem like that.

Why does this choose statement not work in an Access criteria?

I really don't know what I did wrong...I was following advice from a blog post stating that this code would allow me to keep Access from breaking up my criteria (I have a ton of criteria and it was making this statement into four separate lines and adding columns.) Here's my code right now.
Choose(1,(([dbo_customerQuery].[store])>=[forms]![TransactionsForm]![txtStoreFrom] Or
[forms]![TransactionsForm]![txtStoreFrom] Is Null) And (([dbo_customerQuery].[store])
<=[forms]![TransactionsForm]![txtStoreTo] Or [forms]![TransactionsForm]![txtStoreTo]
Is Null))
The statement inside of the choose is definitely correct so am I using "Choose" wrong? I don't get it, the blog post used it exactly this way. When I execute queries, no matter what those fields do, I end up getting no results. The query is supposed to filter based on a date range, taking null values into account
My concern is that you are trying to work around a bad design. You may get this immediate issue solved to some degree, and continue to build the bad design. Access is flexible, and forgiving, but there's a big price eventually -- maybe you're already there.
I realize this is not an answer. It may seem rude -- I apologize. But I think the general advice may help you. I'll tag this "community wiki" since I'm not contributing to a programming solution.
It might be the placing of the parens, try this:
Choose(1,(([dbo_customerQuery].[store]>=[forms]![TransactionsForm]![txtStoreFrom]) Or
[forms]![TransactionsForm]![txtStoreFrom] Is Null) And (([dbo_customerQuery].[store]
<=[forms]![TransactionsForm]![txtStoreTo]) Or [forms]![TransactionsForm]![txtStoreTo]
Is Null))
I have moved two closing parentheses.
I have found what it was now. My statement
Choose(1,(([dbo_customerQuery].[store])>=[forms]![TransactionsForm]![txtStoreFrom] Or
[forms]![TransactionsForm]![txtStoreFrom] Is Null) And (([dbo_customerQuery].[store])
<=[forms]![TransactionsForm]![txtStoreTo] Or [forms]![TransactionsForm]![txtStoreTo]
Is Null))
was correct, the problem was I assumed it would work as a criteria, but it actually had to be done exactly as in the blog post posted above. It had to be posted directly as the FIELD, with "<> False" being the criteria.
Once done, it did stay on one line, and it worked just as expected.

Converting an SQL Statement into R Code Without SQLDF

I'm a new-ish programmer in R and I'm having a bit of an issue with some SQL code.
What I want to do is to convert this operation to base R code. I know it's quite complicated and I tried using merge but I didn't really manage to get anywhere.
Censored <- sqldf("SELECT Censored1.ModelYearID, Censored1.InServiceDate, Censored1.Censored, Censored1.VIN
FROM Censored1 LEFT JOIN Claims ON Censored1.VIN = Claims.VIN
GROUP BY Censored1.ModelYearID, Censored1.InServiceDate, Censored1.Censored, Censored1.VIN, Claims.VIN
HAVING (((Claims.VIN) Is Null))")
The reason I want to do this is because I have ~1600 different Claims tables in a data frame list (df_listl) which are named like this:
LabourOperation.ModelYearID e.g. Q123456.1997, Q234567.1998
and I need to run this query for every one of these tables, putting each of the comparable censored tables in the same kind of list.
If anyone could help me with this, that would be great. It's a bit complicated and I'm really struggling as I've only just learnt that you can put data frames in lists!
I was thinking that lapply might be a good way to go but I'm not very good with functions yet.
Thank you in advance :D

Learning ExecuteSQL in FMP12, a few questions

I have joined a new job where I am required to use FileMaker (and gradually transition systems to other databases). I have been a DB Admin of a MS SQL Server database for ~2 years, and I am very well versed in PL/SQL and T-SQL. I am trying to pan my SQL knowledge to FMP using the ExecuteSQL functionaloty, and I'm kinda running into a lot of small pains :)
I have 2 tables: Movies and Genres. The relevant columns are:
Movies(MovieId, MovieName, GenreId, Rating)
Genres(GenreId, GenreName)
I'm trying to find the movie with the highest rating in each genre. The SQL query for this would be:
SELECT M.MovieName
FROM Movies M INNER JOIN Genres G ON M.GenreId=G.GenreId
WHERE M.Rating=
(
SELECT MAX(Rating) FROM Movies WHERE GenreId = M.GenreId
)
I translated this as best as I could to an ExecuteSQL query:
ExecuteSQL ("
SELECT M::MovieName FROM Movies M INNER JOIN Genres G ON M::GenreId=G::GenreId
WHERE M::Rating =
(SELECT MAX(M2::Rating) FROM Movies M2 WHERE M2::GenreId = M::GenreId)
"; "" ; "")
I set the field type to Text and also ensured values are not stored. But all I see are '?' marks.
What am I doing incorrectly here? I'm sorry if it's something really stupid, but I'm new to FMP and any suggestions would be appreciated.
Thank you!
--
Ram
UPDATE: Solution and the thought process it took to get there:
Thanks to everyone that helped me solve the problem. You guys made me realize that traditional SQL thought process does not exactly pan to FMP, and when I probed around, what I realized is that to best use SQL knowledge in FMP, I should be considering each column independently and not think of the entire result set when I write a query. This would mean that for my current functionality, the JOIN is no longer necessary. The JOIN was to bring in the GenreName, which is a different column that FMP automatically maps. I just needed to remove the JOIN, and it works perfectly.
TL;DR: The thought process context should be the current column, not the entire expected result set.
Once again, thank you #MissJack, #Chuck (how did you even get that username?), #pft221 and #michael.hor257k
I've found that FileMaker is very particular in its formatting of queries using the ExecuteSQL function. In many cases, standard SQL syntax will work fine, but in some cases you have to make some slight (but important) tweaks.
I can see two things here that might be causing the problem...
ExecuteSQL ("
SELECT M::MovieName FROM Movies M INNER JOIN Genres G ON
M::GenreId=G::GenreId
WHERE M::Rating =
(SELECT MAX(M2::Rating) FROM Movies M2 WHERE M2::GenreId = M::GenreId)
"; "" ; "")
You can't use the standard FMP table::field format inside the query.
Within the quotes inside the ExecuteSQL function, you should follow the SQL format of table.column. So M::MovieName should be M.MovieName.
I don't see an AS anywhere in your code.
In order to create an alias, you must state it explicitly. For example, in your FROM, it should be Movies AS M.
I think if you fix those two things, it should probably work. However, I've had some trouble with JOINs myself, as my primary experience is with FMP, and I'm only just now becoming more familiar with SQL syntax.
Because it's incredibly hard to debug SQL in FMP, the best advice I can give you here is to start small. Begin with a very basic query, and once you're sure that's working, gradually add more complicated elements one at a time until you encounter the dreaded ?.
There's a number of great posts on FileMaker Hacks all about ExecuteSQL:
Since you're already familiar with SQL, I'd start with this one: The Missing FM 12 ExecuteSQL Reference. There's a link to a PDF of the entire article if you scroll down to the bottom of the post.
I was going to recommend a few more specific articles (like the series on Robust Coding, or Dynamic Parameters), but since I'm new here and I can't include more than 2 links, just go to FileMaker Hacks and search for "ExecuteSQL". You'll find a number of useful posts.
NB If you're using FMP Advanced, the Data Viewer is a great tool for testing SQL. But beware: complex queries on large databases can sometimes send it into fits and freeze the program.
The first thing to keep in mind when working with FileMaker and ExecuteSQL() is the difference between tables and table occurrences. This is a concept that's somewhat unique to FileMaker. Succinctly, tables store the data, but table occurrences define the context of that data. Table occurrences are what you're seeing in FileMaker's relationship graph, and the ExecuteSQL() function needs to reference the table occurrences in its query.
I agree with MissJack regarding the need to start small in building the SQL statement and use the Data Viewer in FileMaker Pro Advanced, but there's one more recommendation I can offer, which is to use SeedCode's SQL Explorer. It does require the adding of table occurrences and fields to duplicate the naming in your existing solution, but this is pretty easy to do and the file they offer includes a wizard for building the SQL query.