How to use subquery in Append SQL for Access - ms-access-2007

I need to add a subquery in my append SQL and it gives me an error:
Query input must contain at least one table or query.
When I replace the subquery with a constant value, no error is returned.
My code is:
INSERT INTO tblActivity ( RequirementReferenceID, ActivityDate, ActivitySource, ActivityTypeID, ActivityDetails, AffectedFieldID )
SELECT [forms]![frmActivity]![UniqueID] AS Expr1,
Now() AS Expr2,
[forms]![frmActivity]![ChangedBy] AS Expr3,
7 AS Expr4,
(Select RequirementStatus from tblStatus
where tblStatus.RequirementStatusID = [forms]![frmActivity]![NewRequirementStatus]) AS Expr5,
48 AS Expr6;
What am I doing wrong?

I found the answer!
Instead of nesting a second Select query inside my first Select query I transformed the first one to reflect what I needed from the second.
INSERT INTO tblActivity ( RequirementReferenceID, ActivityDate, ActivitySource, ActivityTypeID, ActivityDetails, AffectedFieldID )
SELECT [forms]![frmActivity]![UniqueID], Now(), [forms]![frmActivity]![ChangedBy], 7, RequirementStatus, 48
from tblStatus
where tblStatus.RequirementStatusID = [forms]![frmActivity]![NewRequirementStatus];
This works perfectly.

Related

Snowflake - update with correlated subquery using timediff

I am running this query on Snowflake Database:
UPDATE "click" c
SET "Registration_score" =
(SELECT COUNT(*) FROM "trackingpoint" t
WHERE 1=1
AND c."CookieID" = t."CookieID"
AND t."page" ilike '%Registration complete'
AND TIMEDIFF(minute,c."Timestamp",t."Timestamp") < 4320
AND TIMEDIFF(second,c."Timestamp",t."Timestamp") > 0);
The Database returns Unsupported subquery type cannot be evaluated. However, if I run it without the last two conditions (with TIMEDIFF), it works without problem. I confirmed that the actual TIMEDIFF statements are alright with these queries:
select count(*) from "trackingpoint"
where TIMEDIFF(minute, '2018-01-01', "Timestamp") > 604233;
select count(*) from "click"
where TIMEDIFF(minute, '2018-01-01', "Timestamp") > 604233;
and these work without problem. I don't see a reason why the TIMEDIFF condition shoud prevent the database from returning the result. Any idea what should I alter to make it work?
so using the following setup
create table click (id number,
timestamp timestamp_ntz,
cookieid number,
Registration_score number);
create table trackingpoint(id number,
timestamp timestamp_ntz,
cookieid number,
page text );
insert into click values (1,'2018-03-20', 101, 0),
(2,'2019-03-20', 102, 0);
insert into trackingpoint values (1,'2018-03-20 00:00:10', 101, 'user reg comp'),
(2,'2018-03-20 00:00:11', 102, 'user reg comp'),
(3,'2018-03-20 00:00:13', 102, 'pet reg comp'),
(4,'2018-03-20 00:00:15', 102, 'happy dance');
you can see we get the rows we expect
select c.*, t.*
from click c
join trackingpoint t
on c.cookieid = t.cookieid ;
now there are two ways to get your count, the first as you have it, which is good if your counting only one thing, as all the rules are join filtering:
select c.id,
count(1) as new_score
from click c
join trackingpoint t
on c.cookieid = t.cookieid
and t.page ilike '%reg comp'
and TIMEDIFF(minute, c.timestamp, t.timestamp) < 4320
group by 1;
or you can (in snowflake syntax) move the count to the aggregate/select side,and thus get more than one answer if that's what you need (this is the place I find myself more, thus why I present it):
select c.id,
sum(iff(t.page ilike '%reg comp' AND TIMEDIFF(minute, c.timestamp, t.timestamp) < 4320, 1, 0)) as new_score
from click c
join trackingpoint t
on c.cookieid = t.cookieid
group by 1;
thus plugging this into the UPDATE pattern (see last example in the doc's)
https://docs.snowflake.net/manuals/sql-reference/sql/update.html
you can move to a single subselect instead of a corolated subquery which snowflake doesn't support, which is the error message you are getting.
UPDATE click c
SET Registration_score = s.new_score
from (
select ic.id,
count(*) as new_score
from click ic
join trackingpoint it
on ic.cookieid = it.cookieid
and it.page ilike '%reg comp'
and TIMEDIFF(minute, ic.timestamp, it.timestamp) < 4320
group by 1) as s
WHERE c.id = s.id;
The reason add the TIMEDIFF turns your query into a correlated sub-query, is each row of the UPDATE, now relates to the sub-query results, the correlation. The work around is to make "big but simpler" sub-query and join to that.

Query division returns 0

I am working on a query that devide 2 columns, I tried CAST and CONVERT but still returns 0. Will apperciate your help
SELECT a.Disposition,a.[Disposition Reason Breakdown],a.CSP,b.Total FROM
(
SELECT a.[Disposition],a.[Disposition Reason Breakdown],a.[CSP] FROM
(
SELECT [Disposition],[Disposition Reason Breakdown],COUNT(*) as CSP FROM [dbo].[Disposition]
WHERE [Disposition] <> 'Interested'
GROUP BY [Disposition],[Disposition Reason Breakdown]
) a
)a
INNER JOIN
(
SELECT a.Disposition,SUM(a.CSP) as Total FROM
(
SELECT [Disposition],[Disposition Reason Breakdown],COUNT(*) as CSP FROM [dbo].[Disposition]
WHERE [Disposition] <> 'Interested'
GROUP BY [Disposition],[Disposition Reason Breakdown]
)a
GROUP BY a.Disposition
)b ON a.Disposition = b.Disposition
I am using sql
I solved it, it turns out that I just used the wrong data type which in my case is decimal I should've thought of REAL here is the final query a.CSP/CAST(b.Total as REAL)

SQL subquery in the AND statement

A couple problems.
Solved valid_from_tsp <> max(valid_from_tsp) - how can I get my query to filter based on not being the max date? This idea doesn't work The error being returned is: "Improper use of an aggregate function in a WHERE clause"
My second issue is when I run it without the date, I am returned a syntax error: Syntax error, expected something like 'IN' keyword or 'CONTAINS' keyword between ')' and ')'
What do you see that I don't? Thanks in advance
Edited Query
select
a.*,
b.coverage_typ_cde as stg_ctc
from P_FAR_BI_VW.V_CLAIM_SERVICE_TYP_DIM a
inner join (select distinct etl_partition_id, coverage_typ_cde from
P_FAR_STG_VW.V_CLAIM_60_POLICY_STG where row_Create_tsp > '2013-11-30 23:23:59')b
on (a.etl_partition_id = b.etl_partition_id)
where a.valid_from_tsp > '2013-11-30 23:23:59'
and a.coverage_typ_cde = ' '
and (select * from P_FAR_SBXD.T_CLAIM_SERVICE_TYP_DIM where service_type_id = 136548255
and CAST(valid_from_tsp AS DATE) <> '2014-03-14')
Trouble part: and (select * from P_FAR_SBXD.T_CLAIM_SERVICE_TYP_DIM where service_type_id = 136548255
and CAST(valid_from_tsp AS DATE) <> '2014-03-14')
I am trying to filter by the date on the service_type_id, and I am getting the error in question 2
As for sample data: This is kinda tricky, This query returns many thousands of rows of data. Currently when I do the inner join, I get a secondary unique index violation error. So I am trying to filter out everything but the more recent which could be under that violation (service_type_id is the secondary index)
If I bring back three rows with the service_type_id with three different valid_from_tsp timestamps, I only want to keep the newest one, and in the query, not return the other two.
I don't know about your second question, but your first error is due to using an aggregate function max in a where clause. I'm not really sure what you want to do here, but a quick fix is to replace max(valid_from_tsp) with a subquery that only returns the maximum value.
This is your query:
select a.*, b.coverage_typ_cde as stg_ctc
from P_FAR_BI_VW.V_CLAIM_SERVICE_TYP_DIM a inner join
(select distinct etl_partition_id, coverage_typ_cde
from P_FAR_STG_VW.V_CLAIM_60_POLICY_STG
where row_Create_tsp > '2013-11-30 23:23:59'
) b
on (a.etl_partition_id = b.etl_partition_id)
where a.valid_from_tsp > '2013-11-30 23:23:59' and
a.coverage_typ_cde = ' ' and
(select *
from P_FAR_SBXD.T_CLAIM_SERVICE_TYP_DIM
where service_type_id = 136548255 and
CAST(valid_from_tsp AS DATE) <> '2014-03-14'
);
In general, you cannot have a subquery just there in the where clause with no condition. Some databases might allow a scalar subquery in this context (one that returns one row and one column), but this isn't a scalar subquery. You can fix the syntax by using exists:
where a.valid_from_tsp > '2013-11-30 23:23:59' and
a.coverage_typ_cde = ' ' and
exists (select 1
from P_FAR_SBXD.T_CLAIM_SERVICE_TYP_DIM
where service_type_id = 136548255 and
CAST(valid_from_tsp AS DATE) <> '2014-03-14'
);

SQL Subquery returned more than 1 value

My query causes the following error:
Msg 512, Level 16, State 1, Procedure Item_insupd, Line 17
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
Query:
INSERT INTO [Total_Database].[dbo].[Item]
(
ItemID,
ItemNo,
ItemDescription,
Notes,
StandardCost,
SalesGLAccountID,
ItemTypeID,
Backorderable
)
(
SELECT [nr],
[nr],
[Latijn]+' '+[Subgroep]+' '+CAST([nr] as VARCHAR(255)),
[NL]+' '+[Vorm]+' '+[Kenmerk]+' '+[Hoogte],[Inkoopprijs],
(4),
(case when [Productgroep]='PB' then 1 else 5 end),
(1)
FROM [ACCESDATA].[dbo].[Planten]
);
I suspect this to happen because my subquery does not contain a WHERE, unfortunately I do not know how to construct a correct WHERE clause.
I suspect the problem is in this string (line 26 in your code):
IF NOT (EXISTS (SELECT G.GLAccountID FROM GLAccnt G INNER JOIN Inserted I ON G.GLAccountID = I.SalesGLAccountID))
OR ((SELECT I.COGSGLAccountID FROM Inserted I) IS NOT NULL) AND NOT (EXISTS (SELECT G.GLAccountID FROM GLAccnt G INNER JOIN Inserted I ON G.GLAccountID = I.COGSGLAccountID))
It looks like (SELECT I.COGSGLAccountID FROM Inserted I) return more than one row, so you're getting an error.
You're treating inserted as a one row table (for example, you're getting parameters from it like SELECT #ItemNo = I.ItemNo, #ItemDescription = I.ItemDescription FROM Inserted I, but inserted table can have more than one row. So in your case I think you have 3 options - check that there's only 1 row in inserted, rewrite trigger as set-based, or use cursor.
Here's sql fiddle with somewhat similar example.
If you really only want to insert one row, then You just add Where at the end, followed by some predicate (logical statement) that will be true for only one row in the table the query is reading from.
INSERT INTO [Total_Database].[dbo].[Item](ItemID,
ItemNo,ItemDescription,Notes,StandardCost,SalesGLAccountID,
ItemTypeID,Backorderable)
SELECT [nr],[nr],[Latijn]+' '+[Subgroep]+' '+CAST([nr] as VARCHAR(255)),
[NL]+' '+[Vorm]+' '+[Kenmerk]+' '+[Hoogte],[Inkoopprijs],(4),
(case when [Productgroep]='PB' then 1 else 5 end),(1)
FROM [ACCESDATA].[dbo].[Planten]
Where [SomeColumnName] = [some Value];
... but when performing an Insert using a select to generate the rows to be inserted, you just type the Select statement instead of the Values() clause, without surrounding parentheses. I think that because you had the surrounding parentheses, the query processor assumed you wanted that to be a single value. Do you want to only insert one row of data? or a whole set of data rows ?
INSERT INTO [Total_Database].[dbo].[Item]
(
ItemID,
ItemNo,
ItemDescription,
Notes,
StandardCost,
SalesGLAccountID,
ItemTypeID,
Backorderable
) IN
(
SELECT [nr],
[nr],
[Latijn]+' '+[Subgroep]+' '+CAST([nr] as VARCHAR(255)),
[NL]+' '+[Vorm]+' '+[Kenmerk]+' '+[Hoogte],[Inkoopprijs],
(4),
(case when [Productgroep]='PB' then 1 else 5 end),
(1)
FROM [ACCESDATA].[dbo].[Planten]
);

How to insert bulky value to sql table?

I want to add bulky data from another data below. But I can not do that: error is returned. But areas are the same as another.
declare #hrmtable1 table(musterino int, ekno smallint)
insert into #hrmtable1 (musterino , ekno)
select distinct musterino, ekno
from hareketmuhasebe (nolock)
where islemtarihi >= '20120101'
and isnull(musterino, 0) <> 0
and isnull(musterino, 0) > 9000000
and isnull(ekno,0) <> 0
insert into table1(A,B,C,D,E,. . . . .N)
SELECT DISTINCT
case when ((select count(*) from table1 where musterino=e.musterino) > 0)
then (select top 1 *
from dbo.table1
where musterino = e.musterino
order by ekno desc)
else
(select 100, e.musterino, e.ekno, 0, K, L, M)
from #hrmtable1 e )
end
ERROR:
Msg 120, Level 15, State 1, Line 10
The select list for the INSERT statement contains fewer items than the insert list.
The number of SELECT values must match the number of INSERT columns.
As mentioned in the error the number of columns in insert does not mach the number of value that you are providing
insert into #hrmtable1 (musterino , ekno)
select distinct musterino,ekno
from hareketmuhasebe (nolock)
where islemtarihi >= '20120101'
and isnull(musterino,0) <> 0 and isnull(musterino,0) < 9000000 and isnull(ekno,0) <> 0
Try this:
insert into #hrmtable1 (musterino , ekno)
select distinct musterino,ekno
from hareketmuhasebe (nolock)
where islemtarihi >= '20120101'
and isnull(musterino,0) <> 0 and isnull(musterino,0) < 9000000 and isnull(ekno,0) <> 0
You are having 2 columns in insert & 5 columns in select clause, that is the cause of error.
EDIT: Since you edited the question, still the answer remains the same. Your number of columns in Select statement doesn't match to your insert statement columns in the 2nd part of your code.
In your first statement you are specifying 2 columns and in select you have 5 columns, they should match and that is what the error is telling you exactly.
insert into #hrmtable1 (musterino , ekno)
^^^^^^^ ^^^^
select distinct musterino,ekno,defterid,dovizcinsi, subekodu
^^^^^^^ ^^^ ^^^^ ^^^^^ ^^^^^
From your insert statement it looks like you don't need the last three columns in your Select statement.
The select list for the INSERT statement contains fewer items than the
insert list. The number of SELECT values must match the number of
INSERT columns.
The error itself tells you the story that what you are doing wrong. you have fewer columns in insert statement than to select statement.
From MSDN
The select list of the subquery must match the column list of the
INSERT statement. If no column list is specified, the select list must
match the columns in the table or view being inserted into.
Read more about Inert into