I am relatively new to SQL and having some difficulty understanding how to run a conditional query. For some context, this query is being run with Node/Express using Postgresql.
Situation
If a user selects 'Team A' the query (in the backend) will take the data from one table, while if the user selects 'Team B' it will run the query against a different table. To render the table correctly I need to transpose the data and understand I can achieve this with UNNEST(array[]).
I can run the query successfully with the following code:
SELECT "TeamA" AS "Player",
UNNEST(array['Type1', 'Type2', 'Type2']) AS "Type",
UNNEST(array["Column1", "Column2", "Column3"]) AS "Type2",
UNNEST(array["Column4", "Column5", "Column6"]) AS "Type3",
UNNEST(array["Column7", "Column8", "Column9"]) AS "Type4",
UNNEST(array["Column10", "Column11", "Column12"]) AS "Type5"
FROM sportingdb."TeamAData"
WHERE "TeamA" = '${player}'
However this needs to be dynamic and query a different table if the user selects 'Team A' or 'Team B'.
I have attempted to use the same query with a ternary, however was given a syntax error and am unable to identify where I have gone wrong. I also broke it down as an if else statement as follows:
DO
BEGIN
IF '${TeamA}' = "TeamA" THEN
SELECT "TeamA" AS "Player",
UNNEST(array['Type1', 'Type2', 'Type2']) AS "Type",
UNNEST(array["Column1", "Column2", "Column3"]) AS "Type2",
UNNEST(array["Column4", "Column5", "Column6"]) AS "Type3",
UNNEST(array["Column7", "Column8", "Column9"]) AS "Type4",
UNNEST(array["Column10", "Column11", "Column12"]) AS "Type5"
FROM sportingdb."TeamAData"
WHERE "TeamA" = '${player}'
ELSE
SELECT "TeamB" AS "Player",
UNNEST(array['Type1', 'Type2', 'Type2']) AS "Type",
UNNEST(array["Column1", "Column2", "Column3"]) AS "Type2",
UNNEST(array["Column4", "Column5", "Column6"]) AS "Type3",
UNNEST(array["Column7", "Column8", "Column9"]) AS "Type4",
UNNEST(array["Column10", "Column11", "Column12"]) AS "Type5"
FROM sportingdb."TeamBData"
WHERE "TeamB" = '${player}'
END IF
END
I found this link was somewhat helpful, which I followed to write the above code but arrived with an SQL error [42601]: ERROR: syntax error at or near "BEGIN". I also tried adding the dollar signs as per the example as well as a DECLARE line but this didn't seem to work.
I would truly appreciate any assistance on how I can get this to work. Thanking you in advance!
Related
I've been struggling for a while trying to get FULL-TEXT INDEX and CONTAINS/FREETEXT query working on a MySQL database. I attempted to set it up and test it using phpMyAdmin.
I created a new database (FULL_TEXT_DB) new table (FULLTEXT_TABLE) with 2 columns (AI & TEXT_COL). AI is type 'INT', index is 'PRIMARY' with the auto increment box checked. TEXT_COL is type 'VARCHAR' with the index as 'FULLTEXT' and Index Name is 'id'
I made 2 test rows with text = 'red apple raw' and 'red apple organic'
INSERT INTO `fulltext_table` (`ai`, `text_col`) VALUES ('1', 'red apple raw'), ('2', 'red apple organic');
I attempted to test it with CONTAINS and FREETEXT.
SELECT * FROM fulltext_table WHERE CONTAINS(text_col, 'red apple raw');
SELECT * FROM testing_fulltext WHERE FREETEXT(text_col, 'red');
CONTAINS produced no results and FREETEXT returned an error (Error #1305 "FUNCTION FULL_TEXT_DB.FREETEXT does not exist)
Any help would be greatly appreciated. Perhaps my problem is using phpMyAdmin, but unfortunately that's all I've ever used to create tables and then run them using web PHP code. I am a SQL novice. Thanks!
I am a relative beginner in SQL (Learned and forgotten many times) and entirely self taught so please excuse my likely lack of proper terminology. I made a query that pulls items that have been returned, each items' row has a return code. Here is a result sample:
In the final report(Created with Visual Studio), I would like to be able to have a count of returns by return type but I would need to consolidate the 40 or so return codes into 4 or 5 return type groups. So RET_CODE values ) and . are both product quality issues and would count in the "Product Quality" row.
I could use some help with what the best way to accomplish this would be.
Thank You
Andrew
The bad way!
You could do this by creating the grouping within your SQL statement with something like
SELECT
*,
CASE
WHEN RET_CODE IN ('.', ')') THEN 'Quality Error'
WHEN RET_CODE IN ('X', 'Y', 'Z') THEN 'Some Other error'
ELSE [Desc1]
END AS GroupDescription
FROM myTable
The problem with this approach is that you have to keep repeating it every time you want to something similar.
The better option. (but not perfect!)
Assuming you do not already have such a table...
Create a table that contains the grouping. You can use this in the future whenever you need to do this kind of thing.
For example.
CREATE TABLE dbo.MyErrorGroupTable (RET_CODE varchar(10), GroupDescription varchar(50))
INSERT INTO dbo.MyErrorGroupTable VALUES
('.', 'Quality Error'),
(')', 'Quality Error'),
('X', 'Some Other Error'),
('Y', 'Some Other Error'),
('.', 'Some Other Error'),
('P', 'UPS Error'),
('A', 'PAck/Pick Error')
etc....
Then you can simply join to this table and use the GroupDescription in your report
e.g.
SELECT
a.*, b.GroupDescription
FROM myTable a
JOIN MyErrorGroupTable b ON a.RET_CODE = b.RET_CODE
Hope this helps...
You're looking for the GROUP BY clause.
I'm trying to create new view from 2 different table of same schema. This is my query, let me know if I'm missing anything. When I check the syntax it is fine and test it, throws 00933 error.
CREATE OR REPLACE FORCE VIEW "APDA"."countview"
(
"dealidint", "companyidint", "nametxt", "county", "street",
"state", "city", "zip", "geocodelatdec", "geocodelongdec",
"volidint", "reportdate", "vehicletotalint", "salvagetotalint"
)
AS
SELECT a."dealidint",
a."companyidint",
a."nametxt",
a."county",
a."street",
a."state",
a."city",
a."zip",
a."geocodelatdec",
a."geocodelongdec",
c."dealervolumeidint",
c."reportdate",
c."vehicletotalint",
c."salvagetotalint"
FROM "APDA"."company" a
JOIN
"APDA"."volume" c
ON c."dealidint" = a."dealidint";
I don't see the reason. The only suspect thing I notice is the two blank lines. In SQLPlus I don't think these would cause this error, but they would cause the command to be misinterpreted.
My suggestions are:
- try a different tool. If you are getting the error in SQL Developer, try it in SQLPlus. It won't necessarily work, but you might get different feedback.
- reduce it to a minimal statement that works, then add elements back in one at a time until the error occurs
your column name "volidint" not in selected column, i see "dealervolumeidint" select vs "volidint".
Column name "volidint" is not available in your below select query. Please correct that by using "As".
CREATE OR REPLACE FORCE VIEW "APDA"."countview"
(
"dealidint", "companyidint", "nametxt", "county", "street",
"state", "city", "zip", "geocodelatdec", "geocodelongdec",
"volidint", "reportdate", "vehicletotalint", "salvagetotalint"
)
AS
SELECT a."dealidint",
a."companyidint",
a."nametxt",
a."county",
a."street",
a."state",
a."city",
a."zip",
a."geocodelatdec",
a."geocodelongdec",
c."dealervolumeidint" as "volidint",
c."reportdate",
c."vehicletotalint",
c."salvagetotalint"
FROM "APDA"."company" a
JOIN
"APDA"."volume" c
ON c."dealidint" = a."dealidint";
Thanks to all you pitched to answer my query. The one I have shared is a stripped down query with the same syntax. The query was fine but my actual query has an extra character on the join. Which is like - "APDA"."vvolume".
After that I was able to create the view.
Thanks again.
I'm making a tiny webapp to see what are the pub's specials around you and I have a very silly problem with my SQL query to fusion table.
Here is my table and her is my query:
ST_INTERSECTS(address, CIRCLE(LATLNG(-33.898672999999995, 151.2063809), 300))
AND type IN ('food','drinks')
AND days CONTAINS 'tuesday'
AND from <= 2000
AND to >= 2000
My problem is with the from and to, if I remove them my query is fine and if I simplify them (remove from and put just to > 0) my query is still wrong.
As you can see in my fusion table, from and to are both numbers so I really don't get what's wrong.
EDIT:
So I'm using https://developers.google.com/apis-explorer/#p/fusiontables/v2/fusiontables.query.sql to test my queries:
Good query (200 OK):
SELECT *
FROM 1BHnaan3YfSDq9_LzjthDXjj5dzJZANjLSb8JHPl5
WHERE
ST_INTERSECTS(address, CIRCLE(LATLNG(-33.898672999999995, 151.2063809), 300))
AND type IN ('food','drinks')
AND days CONTAINS 'tuesday'
Bad query:
SELECT *
FROM 1BHnaan3YfSDq9_LzjthDXjj5dzJZANjLSb8JHPl5
WHERE
ST_INTERSECTS(address, CIRCLE(LATLNG(-33.898672999999995, 151.2063809), 300))
AND type IN ('food','drinks')
AND days CONTAINS 'tuesday'
AND from <= 1619
AND to >= 1619
I get this error but I don't see what's wrong because <= is in the docs:
{
"error": {
"errors": [
{
"domain": "fusiontables",
"reason": "badQueryCouldNotParse",
"message": "Invalid query: Parse error near 'from' (line 1, position 218).",
"locationType": "parameter",
"location": "q"
}
],
"code": 400,
"message": "Invalid query: Parse error near 'from' (line 1, position 218)."
}
}
from & to are reserved words in fusion table, here is the list of reserved words:
AND
ASC
AS
BY
CASE
CIRCLE
CONTAINS
CONTAIN
CREATE
DELETE
DESCRIBE
DESC
DOES
DROP
ENDS
EQUAL
FROM
GROUP
IGNORING
IN
INSERT
INTO
LATLNG
LIKE
LIMIT
MATCHES
NEAR
NOT
OFFSET
ORDER
POLYGON
RECTANGLE
ROWID
SELECT
SET
SHOW
SKIP
ST_DISTANCE
ST_INTERSECTS
STARTS
TABLES
TABLE
TO
UPDATE
VALUES
VIEW
WHERE
WITH
ID
NUMBER
DOCID
STRING
I figured it out because they were blue in the syntax highlighting in my question.
If you try that query from the Fusion Tables UI, you also see no results, because no values match those criteria. The days are "monday" and "tuesday", and the times are 1130-1400 and 1800-2359.
I'm trying to display all such rows of a table STUDENTS which have a value of an attribute, such as COURSE IN a set of given values e.g. 'MS', 'PhD'.
I get the values in the students_controller.rb file using params. I tried to run an Active Record query using where to do the job:
#all_courses = ['MS', 'PhD', 'BA', 'MSc']
#students = Student.where("course IN :courses" , {:courses => params.has_key?(:courses) ? params[:courses].keys : #all_courses})
But I get the following error:
SQLite3::SQLException: near ",": syntax error: SELECT "students".* FROM "students" WHERE (course IN 'MS', 'PhD', 'BA', 'MSc')
I think the error might be due to the absence of ; at the end of the SQL query generated by Active Record, but I cannot do anything to get that semicolon at the end.
You need to use parentheses: "course IN (:courses)"