How do i limit the number of rows updated in postgres - postgresql

I am trying to update records in customer table by limiting them to n number of records but i am having an error when i am using offset and limit keywords.
Where do i put
offset 0 limit 1
in update statement sub query as the sub query is like:
update customer set name = 'sample name' where customer_id in (142, 143, 144, 145 offset 0 limit 1);
When i tried executing update statement above, i get an error:
ERROR: syntax error at or near "offset"
Note: limit does not have to be 1, it can be any number and same is true for offset

offset and limit work on rows, not on a list.
You can transform the in() clause to use a subquery that return a row from each of your input
update customer
set name = 'sample name'
where customer_id in (select unnest(array[142, 143, 144, 145]) offset 0 limit 1);

Related

How to add pipeline().parameters to Lookup in Azure Data Factory?

I have Lookup Activity in Azure Data Factory.
I have parameter "offset", which have initial value 5.
I want to use parameter value as Integer value in Lookup query, but failing. Please advice.
Original Static Lookup Query:
SELECT *
FROM sales.[Customers]
ORDER BY CustomerId OFFSET 5 ROWS FETCH NEXT 10 ROWS ONLY
--Parameterized Lookup Query:
SELECT *
FROM sales.[Customers]
ORDER BY CustomerId #concat('OFFSET ', pipeline().parameters.offset,' ROWS FETCH NEXT 10 ROWS ONLY')
Error of ADF for parameterized Lookup:
A database operation failed with the following error: 'Incorrect syntax near
'#concat'.',Source=,''Type=System.Data.SqlClient.SqlException,Message=Incorrect syntax near
'#concat'.,Source=.Net SqlClient Data
Provider,SqlErrorNumber=102,Class=15,ErrorCode=-2146232060,State=1,Errors=
[{Class=15,Number=102,State=1,Message=Incorrect syntax near '#concat'.,},],'
Put the entire SQL statement in an expression (using the Expression Builder):
#concat('SELECT * FROM sales.[Customers] ORDER BY CustomerId OFFSET ', pipeline().parameters.offset, ' ROWS FETCH NEXT 10 ROWS ONLY')
You can directly call the parameter as well
SELECT *
FROM sales.[Customers]
ORDER BY CustomerId OFFSET #{pipeline().parameters.offset} ROWS FETCH NEXT 10 ROWS ONLY

Can't understand why using CAST errors out but using CONVERT does not?

The following code that executes without any issue:
Select
#ICDCodes.ICD_Code,
#ICDCodes.Description,
Count(#DiseaseIndex.VstIntID) AS 'Total Count',
Sum(DATEDIFF(dd,#DiseaseIndex.AdmitDtSrt,#DiseaseIndex.DschrgDtTm )) as 'Total LOS',
ISNULL(AVG(CONVERT(NUMERIC(8,2),DATEDIFF(DAY,#DiseaseIndex.AdmitDtSrt,#DiseaseIndex.DschrgDtTm))),0) as 'Total Avg LOS'
FROM #DiseaseIndex LEFT JOIN #ICDCodes on #DiseaseIndex.VstIntID = #ICDCodes.VstIntID
WHERE ICD_Type IN ('P','S')
GROUP BY #ICDCodes.ICD_Code, #ICDCodes.Descriptio
but this code throws an error:
SELECT
#ICDCodes.ICD_Code,
#ICDCodes.Description,
Count(#DiseaseIndex.VstIntID) AS 'Total Count',
Sum(CAST(DATEDIFF(dd,#DiseaseIndex.AdmitDtSrt,#DiseaseIndex.DschrgDtTm )AS NUMERIC(8,2))) AS 'Total LOS',
ISNULL(CAST(DATEDIFF(DAY,#DiseaseIndex.AdmitDtSrt,#DiseaseIndex.DschrgDtTm) AS NUMERIC(8,2)),0) as 'Total Avg LOS'
FROM #DiseaseIndex LEFT JOIN #ICDCodes on #DiseaseIndex.VstIntID = #ICDCodes.VstIntID
WHERE ICD_Type IN ('P','S')
GROUP BY #ICDCodes.ICD_Code, #ICDCodes.Description`
This is the Error it generates:
Msg 8120, Level 16, State 1, Line 191
Column '#DiseaseIndex.AdmitDtSrt' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Msg 8120, Level 16, State 1, Line 191
Column '#DiseaseIndex.DschrgDtTm' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Basically it is the same code with the exception that one set uses CAST() and the other one uses CONVERT().
Can someone explain why the CAST requires adding the dates to the GROUP BY statement while the CONVERT does not?
Thanks in advance
Update
In the second query you've forgot the AVG:
first query:
ISNULL(AVG(CONVERT(NUMERIC(8,2),DATEDIFF(DAY,#DiseaseIndex.AdmitDtSrt,#DiseaseIndex.DschrgDtTm))),0) as 'Total Avg LOS
second query:
ISNULL(CAST(DATEDIFF(DAY,#DiseaseIndex.AdmitDtSrt,#DiseaseIndex.DschrgDtTm) AS NUMERIC(8,2)),0) as 'Total Avg LOS'
First version:
(This was correct for the first version of the question.)
This is because you use NUMERIC(8,2) in the convert, but DECIMAL(8,2) in the cast.
Though numeric and decimal are documented to be interchangeable synonyms, having a numeric in he group by clause and a decimal in the select clause will raise that error.
Here is a simple demo:
DECLARE #T AS TABLE
(
col1 int,
col2 int
)
INSERT INTO #T VALUES
(1,1),(2,1),(3,1),
(4,2),(5,2),(6,2),
(7,3)
SELECT CAST(Col2 as NUMERIC(8,2)),
AVG(Col1)
FROM #T
GROUP BY CONVERT(DECIMAL(8,2), Col2)
Results:
Column '#T.col2' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
However, if you change the select to decimal or the group by to numeric, the error message is gone and the select returns the result set:
SELECT CAST(Col2 as DECIMAL(8,2)),
AVG(Col1)
FROM #T
GROUP BY CONVERT(DECIMAL(8,2), Col2)
Results:
1.00 2
2.00 5
3.00 7
See a live demo on rextester

select maximum column name from different table in a database

I am comparing from different table to get the COLUMN_NAME of the MAXIMUM value
Examples.
These are example tables: Fruit_tb, Vegetable_tb, State_tb, Foods_tb
Under Fruit_tb
fr_id fruit_one fruit_two
1 20 50
Under Vegetables_tb (v = Vegetables)
v_id v_one V_two
1 10 9
Under State_tb
stateid stateOne stateTwo
1 70 87
Under Food_tb
foodid foodOne foodTwo
1 10 3
Now here is the scenario, I want to get the COLUMN NAMES of the max or greatest value in each table.
You can maybe find out the row which contains the max value of a column. For eg:
SELECT fr_id , MAX(fruit_one) FROM Fruit_tb GROUP BY fr_id;
In order to find the out the max value of a table:
SELECT fr_id ,fruit_one FROM Fruit_tb WHERE fruit_one<(SELECT max(fruit_one ) from Fruit_tb) ORDER BY fr_id DESC limit 1;
A follow up SO for the above scenario.
Maybe you can use GREATEST in order to get the column name which has the max value. But then what I'm not sure is whether you'll be able to retrieve all the columns of different tables at once. You can do something like this to retrieve from a single table:
SELECT CASE GREATEST(`id`,`fr_id`)
WHEN `id` THEN `id`
WHEN `fr_id` THEN `fr_id`
ELSE 0
END AS maxcol,
GREATEST(`id`,`fr_id`) as maxvalue FROM Fruit_tb;
Maybe this SO could help you. Hope it helps!

The command has not been executed - Republicated With New Informations - MATCH Clause

I have a Orientdb Database with 2 vertex
Pesquisador with 1 million records
Publicacao with 1 million records too
and an Edge COLABORA_COM with 6,239,382
I need select thousand researchers with the highest number of publications.
I execute the command
SELECT psq1.psq_nome AS nomePesquisador, COUNT(pub1) AS qtdPub
FROM (
MATCH
{class:Pesquisador, as:psq1}.outE("PUBLICOU").inV(){as:pub1}
RETURN psq1, pub1
)
GROUP BY psq1
ORDER BY qtdPub DESC, nomePesquisador
LIMIT 1000;
then there are the error "The command has not been executed"
But if a execute the query
SELECT ordem, out.psq_nome, out.psq_data_nascimento
FROM PUBLICOU
WHERE in.pub_id = 5022
ORDER BY ordem;
the query execute ok
is there an error of memory with MATCH?
Should I change the memory settings?

T SQL Group By Having Count of returning wrong data

I have a complex t-sql query "for me anyway" that isn't functioning the way I need it to.
The query is designed to return simular records unioned across two databases that have simular records in each database.
If a product fails, it will be assigned a "Failed" in one DB, or a "PF" in the other DB. "PR" means "PRODUCT READY" in both.
I am trying to return a list that includes only "Failed or PF" data that has < two records based on the ProdNo column.
"This is to prompt the employee to test the product again", if 2 records exist in either DB, no action is needed."
My query breaks down when I try to limit the results to show only entries that have less than 2 duplicate "ProdNo" values.
In other words, a product is produced and given a ProdNo number. After testing, it can be marked as a PR, PF, or Failed.
My query should never produce any results with PR, yet when a test is performed several days after the original test, PR values appear in my results.
Here is the query with notes.
-- 1st half of union query
-- Find all run failed's that do not have a PR'ed 2nd test.
Declare #daysback int
set #daysback = -2
select min(sid3)as 'ProdNo',
min([Timestamp])as 'TimeS',
min(Burn) as 'type',
min(Mixer) as 'Mixer'
from [Stat].[dbo].[oedata]
where sid3 IN
(
-- Find run faileds and PRs in Stat db
SELECT [sid3]
from [Stat].[dbo].[oedata]
where (type ='wos') and (burn = 'failed')
and (Flag = '128')
)
--- Limit Results to return only instances of 1 record
AND [Timestamp] > DATEADD( d, #daysback, getdate())
group by Sid3
having COUNT(Sid3) = 1
union all
-- Find PF's in CompanyMES MLab DB
select min(mProd_ProdNumber)as 'ProdNo',
min([Timestamp])as 'TimeS',
min(CheckType) as 'type',
min(Mixer) as 'Mixer'
from [CompanyMES].[dbo].[mLab]
where mProd_ProdNumber IN
(
-- Find failed DFs or scrap wos products
SELECT [mProd_ProdNumber]
from [CompanyMES].[dbo].[mLab]
where (CheckType = 'PF' )
)
-- Limit Results to instances with only 1 record
AND [Timestamp] > DATEADD( d, #daysback, getdate())
group by mProd_ProdNumber
having COUNT(mProd_ProdNumber) < 2
order by TimeS Desc
--------------------------------------------------------------------------
Example data and results:
ProdNo Type
=================
'1111' 'PF'
'1111' 'PR'
'1112' 'PR'
'1113' 'PF'
'1114' 'Failed'
ProdNo 1111 shouldn't return anything as it has 2 records as well as a PR exists.
1113 and 1114 should return results as they both have only 1 record as well as have PF and Failed Types
I think the issue is that you are applying a filter on the Timestamp in your outer queries, but not the inner one where you are filtering the Product Numbers. So, for 1111 and 1112, it could have a 'PF' (or 'Failed') outside of your timestamp filtered range, but only 'PR' inside of it (in one of the tables).