I currently have two identical tables (As far as columns) in my access database. I setup a form that allows a user to enter an ID and search through ONE of the tables.
I am trying to have it search through a second table as well, but my query doesn’t return results from BOTH tables. I am only able to retrieve results from the first table.
I used query design to build my query which was basically just selecting the table I need and bringing down all the fields in the criteria section. When I tried to build the second query, I selected both tables and matched the ID’s from both tables, but the results were not correct (ID existed in both tables, but only showed ID from one table).
Private Sub cmdSearch_Click()
If Nz(comboID, "") <> "" Then
'DoCmd.OpenQuery "Inquiries Query", acViewNormal, acReadOnly
DoCmd.OpenQuery "both tables", acViewNormal, acReadOnly
Else
' If Nz(txtReportDate, "") = "" Then
MsgBox "NOTICE! Please enter a ID"
Exit Sub
End If
End Sub
I think what you want is a union all query.
"SELECT * FROM Table1 WHERE ID = " & comboID.value & _
"UNION ALL SELECT * FROM Table2 WHERE ID = " & comboID.value & ";"
This would runs two separate select queries and combine all the columns that are the same.
Note: if you have the exact same record in both tables it will show up twice.
Related
I have a table Design and a view on that table called ArchivedDesign. The view is declared as:
CREATE OR REPLACE VIEW public."ArchivedDesign" ("RootId", "Id", "Created", "CreatedBy", "Modified", "ModifiedBy", "VersionStatusId", "OrganizationId")
AS
SELECT DISTINCT ON (des."RootId") "RootId", des."Id", des."Created", des."CreatedBy", des."Modified", des."ModifiedBy", des."VersionStatusId", des."OrganizationId"
FROM public."Design" AS des
JOIN public."VersionStatus" AS vt ON des."VersionStatusId" = vt."Id"
WHERE vt."Code" = 'Archived'
ORDER BY "RootId", des."Modified" DESC;
Then, I have a large query which gets a short summary of latest changes, thumbnails, etc. The whole query is not important, but it contains two almost identical subqueries - one for the main table and and one for the view.
SELECT DISTINCT ON (1) x."Id",
TRIM(con."Name") AS "Contributor",
extract(epoch from x."Modified") * 1000 AS "Modified",
x."VersionStatusId",
x."OrganizationId"
FROM public."Design" AS x
JOIN "Contributor" AS con ON con."DesignId" = x."Id"
WHERE x."OrganizationId" = ANY (ARRAY[]::uuid[])
AND x."VersionStatusId" = ANY (ARRAY[]::uuid[])
GROUP BY x."Id", con."Name"
ORDER BY x."Id";
and
SELECT DISTINCT ON (1) x."Id",
TRIM(con."Name") AS "Contributor",
extract(epoch from x."Modified") * 1000 AS "Modified",
x."VersionStatusId",
x."OrganizationId"
FROM public."ArchivedDesign" AS x
JOIN "Contributor" AS con ON con."DesignId" = x."Id"
WHERE x."OrganizationId" = ANY (ARRAY[]::uuid[])
AND x."VersionStatusId" = ANY (ARRAY[]::uuid[])
GROUP BY x."Id", con."Name"
ORDER BY x."Id";
Link to SQL fiddle: http://sqlfiddle.com/#!17/d1d0f/1
The query is valid for the table, but fails for the view with an error column x."Modified" must appear in the GROUP BY clause or be used in an aggregate function. I don't understand why there is a difference in the behavior of those two queries? How do I fix the view query to work the same way as the table query?
My ultimate goal is to replace all table sub-queries with view sub-queries so we can easily separate draft, active and archived designs.
You get that error because when you query the table directly, Postgres is able to identify the primary key of the table and knows that grouping by it is enough.
Quote from the manual
When GROUP BY is present, or any aggregate functions are present, it is not valid for the SELECT list expressions to refer to ungrouped columns except within aggregate functions or when the ungrouped column is functionally dependent on the grouped columns, since there would otherwise be more than one possible value to return for an ungrouped column. A functional dependency exists if the grouped columns (or a subset thereof) are the primary key of the table containing the ungrouped column
(emphasis mine)
When querying the view, Postgres isn't able to detect that functional dependency that makes it possible to have a "shortened" GROUP BY when querying the table directly.
I am trying to join two tables within a database, based upon a matching postcode, but am struggling where there are multiple postcodes relating to a single row of data.
i.e. table 1 has 2 columns (a unique ID and postcodes). It is possible for a record to have just a single postcode in this column or multiple postcodes in comma-separated form.
table 2 also has two columns (development description and postcode). In this table the postcode column can have only one postcode.
I would like to identify & join where the postcode from table 2 matches or is included within the relevant column in table 1. I have been able to do so where there is a single postcode within each column, but am currently unable to do so where there are multiple postcodes in table 1.
The below code brings back the matches where there is a single postcode.
SELECT t1.id,
t1.postcodes,
t2.dev_description,
t2.postcode
FROM table1 AS t1
INNER JOIN table2 AS t2
ON t2.postcode LIKE t1.postcodes
WHERE t2.postcode = 'XXX XXX'
I have tried using '%'|| ||'%' and various other functions, but am at a bit of a loss to be honest.
If someone could help it would be great!
Thanks
You could join on:
',' || t1.postcodes || ',' like '%,' || t2.postcode || ',%'
This would expand to:
',1234AB,2345AB,3456AB,' like '%,1234AB,%'
Or you can use string_to_array and the #> contains operator:
string_to_array(t1.postcodes, ',') #> array[t2.postcode]
This expands to:
array['1234AB','2345AB','3456AB'] #> array['1234AB']
Hmmm, I've never joined two tables using ON and LIKE... Anyway, look up the command STRPOS.
Something like this perhaps:
...
OR (STRPOS(t1.postcodes, t2.postcode) > 0)
...
I am getting following error while using named query blog.findBlogs
"Your select and having clauses must only include aggregates or values that also appear in your grouping clause."
In select clause I have used b.id so it must allow to perform this query without error. I also tried same query from mysql workbench and its working perfectly fine.
#NamedQueries( value = {
#NamedQuery (name = "blog.findBlogs", query = "SELECT " +
"NEW com.vo.Blog(b.id, b.blogId, b.createDate, b.tags, b.url, COUNT(r.emotion)) " +
"FROM Blog b JOIN b.rates r " +
"GROUP BY b.id")
})
regards, Amit J.
In general, a GROUP BY query in SQL must obey a rule that everything which appears in the SELECT clause must either appear in the GROUP BY clause or be inside an aggregate function, such as COUNT.
I also tried same query from mysql workbench and its working perfectly fine.
It turns out that MySQL is one of a few databases which does not enforce this rule. But JPA appears to not allow this, so it fails for you running from JPA even though the underlying database is a lax version of MySQL.
Here is how you can modify your code to run without error:
#NamedQueries( value = {
#NamedQuery (name = "blog.findBlogs", query = "SELECT " +
"NEW com.vo.Blog(b.id, COUNT(r.emotion)) " +
"FROM Blog b JOIN b.rates r " +
"GROUP BY b.id")
})
If you're wondering what the logical problem with your original query was, it is that, for a given b.id value, JPA cannot figure out which blog, date, and tags value to choose for that group.
i have a database table with repetitive values in every cell and also same values separated by commas in particular cell, if i need to count all the occurrences of particular name (ex : Facebook) what query i must use(amazon red shift)
A typical SQL query would be:
select count(1) from table t1 where t1.column_name = 'Facebook';
This is if the data cells contain just that word exactly.
Or you might have:
select count(1) from table t1 where t1.column_name like '%Facebook%';
This is if you want to count rows containing word 'Facebook' (among other strings).
Preliminaries:
Our application can read data from an attached client SQL Server 2005 or 2008 database but make no changes to it, apart from using temp tables. We can create tables in our own database on their server.
The solution must work in SQL Server 2005.
The Schema:
Here is a simplified idea of the schema.
Group - Defines characteristics of a group of locations
Location - Defines characteristics of one geographic location. It links to the Group table.
GroupCondition - Links to a Group. It defines measures that apply to a subset of locations belonging to that group.
GroupConditionCriteria - Links to GroupCondition table. It names attributes, values, relational operators and boolean operators for a single phrase in a where clause. The named attributes are all fields of the Location table. There is a sequence number. Multiple rows in the GroupConditionCriteria must be strung together in proper sequence to form a full filter condition. This filter condition is implicitly restricted to those Locations that are part of the group associated with the GroupCondition. Location records that satisfy the filter criteria are "Included" and those that do not are "Excluded".
The Goal:
Many of our existing queries get attributes from the location table. We would like to join to something (table, temp table, query, CTE, openquery, UDF, etc.) that will give us the GroupCondition information for those Locations that are "Included". (A location could be included in more than one rule, but that is a separate issue.)
The schema for what I want is:
CREATE TABLE #LocationConditions
(
[PolicyID] int NOT NULL,
[LocID] int NOT NULL,
[CONDITIONID] int NOT NULL,
[Satisfies Condition] bit NOT NULL,
[Included] smallint NOT NULL
)
PolicyID identifies the group, LocID identifies the Location, CONDITIONID identifies the GroupCondition, [Satisfies Condition] is 1 if the filter includes the location record. (Included is derived from a different rule table with forced overrides of the filter condition. Not important for this discussion.)
Size of Problem:
My best effort so far can create such a table, but it is slow. For the current database I am testing, there are 50,000 locations affected (either included or excluded) by potentially matching rules (GroupConditions). The execution time is 4 minutes. If we do a periodic refresh and use a permanent table, this could be workabble, but I am hoping for something faster.
What I tried:
I used a series of CTEs, one of which is recursive, to concatenate the several parts of the filter condition into one large filter condition. As an example of such a condition:
(STATECODE = 'TX' AND COUNTY = 'Harris County') OR STATECODE = 'FL'
There can be from one to five fields mentioned in the filter condition, and any number of parentheses used to group them. The operators that are supported are lt, le, gt, ge, =, <>, AND and OR.
Once I have the condition, it is still a text string, so I create an insert statement (that will have to be executed dynamically):
insert into LocationConditions
SELECT
1896,
390063,
38,
case when (STATECODE = 'TX' AND COUNTY = 'Harris County') OR STATECODE = 'FL' then 1
else 0
end,
1
FROM Location loc
WHERE loc.LocID = 390063
I first add the insert statements to their own temp table, called #InsertStatements, then loop through them with a cursor. I execute each insert using EXEC.
CREATE TABLE #InsertStatements
(
[Insert Statement] nvarchar(4000) NOT NULL
)
-- Skipping over Lots of complicated CTE's to add to #InsertStatements
DECLARE #InsertCmd nvarchar(4000)
DECLARE InsertCursor CURSOR FAST_FORWARD
FOR
SELECT [Insert Statement]
FROM #InsertStatements
OPEN InsertCursor
FETCH NEXT FROM InsertCursor
INTO #InsertCmd
WHILE ##FETCH_STATUS = 0
BEGIN
--PRINT #InsertCmd
EXEC(#InsertCmd)
FETCH NEXT FROM InsertCursor
INTO #InsertCmd
END
CLOSE InsertCursor
DEALLOCATE InsertCursor
SELECT *
FROM #LocationConditions
ORDER BY PolicyID, LocID
As you can imagine, executing 50,000 dynamic SQL inserts is slow. How can I speed this up?
you have to insert each row individually? you can't use
insert into LocationConditions
SELECT
PolicyID,
LocID,
CONDITIONID,
case when (STATECODE = 'TX' AND COUNTY = 'Harris County') OR STATECODE = 'FL' then 1
else 0
end,
Included
FROM Location loc
? You didn't show how you were creating your insert statements, so I can't tell if it's dependent on each row or not.