Postgres - get LEAST of 2 COUNTs - postgresql-9.6

I would like to find the smallest of 2 table sizes like this:
create function least_func() returns void as $$
declare
result INT;
begin
select least(
select count(*) from my_table,
select count(*) from my_other_table) into result;
end $$ language plpgsql;
This does not compile:
syntax error at or near "select"
LINE 7: select count(*) from my_table,
What's the problem with this function?

You need to put parentheses around your select statements.
select least(
(select count(*) from my_table),
(select count(*) from my_other_table)) into result;

Related

Is there any way to append the variable in big query select in stored procedure

I am trying to call the variable in a select query like below:
BEGIN
DECLARE TGT_LOAD_STATUS_TBL STRING;
SET TGT_LOAD_STATUS_TBL=''||PROJ_ID||'.'||TGT_SCHEMA||'.'||LOAD_STATUS_TBL||'';
FOR FETCH_TEST IN (select col1 from TGT_LOAD_STATUS_TBL WHERE LOAD_STATUS='N')
DO
INSERT INTO project.datasetid.table VALUES(FETCH_TEST.col1);
END FOR;
END
Is there any way to append the variable in a select query?
You can use build your SQL statement by concatenating some strings together and then execute it using EXECUTE IMMEDIATE. This is exactly the use case that EXECUTE IMMEDIATE exists for
I don't think it's a good practice to update a table one by one within a loop.
Instead consider a bulk update using a dynamic sql like below
EXECUTE IMMEDIATE FORMAT("""
INSERT INTO table1
SELECT col1 FROM `%s` WHERE LOAD_STATUS='N'
""", TGT_LOAD_STATUS_TBL);
Test Query:
DECLARE TGT_LOAD_STATUS_TBL DEFAULT 'table2';
CREATE TEMP TABLE table1 (col1 STRING);
CREATE TEMP TABLE table2 AS
SELECT 'a' col1, 'N' LOAD_STATUS UNION ALL
SELECT 'b', 'Y' UNION ALL
SELECT 'c', 'N' UNION ALL
SELECT 'd', 'N' UNION ALL
SELECT 'e', 'N' ;
EXECUTE IMMEDIATE FORMAT("""
INSERT INTO table1
SELECT col1 FROM `%s` WHERE LOAD_STATUS='N'
""", TGT_LOAD_STATUS_TBL);
SELECT * FROM table1;

Solve the syntax error with Redshift operator does not exist and add explicit casts

I am a newbie in the area of redshift data modeling and got myself into trouble with an error.ERROR:
--Final version
syntax error ERROR: operator does not exist: text | record Hint: No
operator matches the given name and argument type(s). You may need to
add explicit type casts. Where: SQL statement "SELECT 'create temp
table ' || $1 || ' as select * from' | $2 |" PL/pgSQL function "egen"
line 36 at execute statement [ErrorId:
1-61dc32bf-0a451f5e2c2639235abb8876]
I am trying to do a simple transformation that gets returned in output when the procedure is called. (As of now I got to find from the documentation we have to use either temp table or cursors to achieve this)
Pseudocode:
I am trying to restrict data to its latest one in (2019) Get the
list of managers create columns if a person is a manager or not from the list.
Return it as a result
Data looks as follows Employee Data
My Select query works fine out of the procedure, please find my complete code below.
CREATE OR REPLACE PROCEDURE EGEN(tmp_name INOUT varchar(256) )
AS $$
DECLARE
--As i have less data managed to create it as an array or please use temp or table and join it with the actual query to perform transformation
MGR_RECORD RECORD;
DATAS RECORD;
item_cnt int := 0;
V_DATE_YEAR int := 0;
BEGIN
--EXECUTE (select cast(extract(year from current_date) as integer)-3) INTO V_DATE_YEAR;
--Manager Records are stored here below
SELECT DISTINCT managerid from "dev"."public"."emp_salary" INTO MGR_RECORD;
SELECT employeeid,
managerid,
promotion,
q_bonus,
d_salary,
case when contractor = 'x'
then 'TemporaryEmployee'
else 'PermanentEmployee'
END as EmployeeType,
-- IFstatement not supported under select query
case when employeeid in (select distinct managerid FROM "dev"."public"."emp_salary" )
then 'Manager'
else 'Ordinary FTE'
END as FTETYPE
FROM "dev"."public"."emp_salary" where cast(extract(year from promotion) as int ) >= 2019 into DATAS;
--COMMIT;
tmp_name := 'ManagerUpdatedTable';
EXECUTE 'drop table if exists ' || tmp_name;
EXECUTE 'create temp table ' || 'ManagerUpdatedTable' || ' as select * from' |DATAS| ;
END;
$$ LANGUAGE plpgsql;
-- Call tests CALL EGEN('myresult'); SELECT * from myresult;
Also, additional query (Can we replace )
case when employeeid in (select distinct managerid FROM "dev"."public"."emp_salary" )
then 'Manager'
else 'Ordinary FTE'
END as FTETYPE
this transform in query to IF , if possible please provide details.
Thanks and Regards,
Gabby

How to skip defined Combinations in sql?

--A=100,B=50,C=200
DECLARE #T1 TABLE (CAT1 VARCHAR(1),CAT2 VARCHAR(1),MinVal int)
INSERT INTO #T1
SELECT 'A','A',100
UNION ALL
SELECT 'A','B',50
UNION ALL
SELECT 'A','C',100
UNION ALL
SELECT 'B','A',50
UNION ALL
SELECT 'B','B',50
UNION ALL
SELECT 'B','C',50
Union all
SELECT 'C','A',100
UNION ALL
SELECT 'C','B',100
UNION ALL
SELECT 'C','C',200
select * from #T1
I have to calculate sum of MinValue
which should include only (AB,AC,BC) as whatever min of AB=BA so need to take one only.
so in result i want to get 3 rows out of 9.
Cat1|Cat2|MinVal
A|B|50
A|C|100
B|C|50
Any help will be highly appreciated.
Earlier i tried the things below but it did not work.
Select * from #T1 where Cat1<>Cat2 and ?
(what condition i need to write to avoid undesired combination.)
Here's a link

How to get foreign key value from Stored Procedure while showing the list.?

Following is the procedure that i have written in my application. But i want the LogSource Column in my list, but i am not able to get it from this stored procedure.
CREATE PROCEDURE [dbo].[GetApplicationLogs]
-- Add the parameters for the stored procedure here
#Skip int,
#Pagesize int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
WITH TableDatawithRowNumber AS
( SELECT dbo.ApplicationLog.* ,ROW_NUMBER() OVER (ORDER BY LoggedDate DESC) AS RowNumber,
(SELECT COUNT(*) AS Expr1
FROM ApplicationLog ) AS TotalRecords
from ApplicationLog
)
SELECT * FROM TableDatawithRowNumber
WHERE RowNumber > #Skip AND RowNumber <= (#Pagesize+#Skip)
END
This table doensn't contain a LogSource column but it is having LogSourceID in it which is a foreign key in this table and the primary key in LogSource Table. I want to show that in my list but i am not able to get it in the view. I can only use LogSourceId but not LogSource. So please help me.
I think you just need to do a left join on the LogSource table
WITH TableDatawithRowNumber AS
( SELECT dbo.ApplicationLog.* ,ROW_NUMBER() OVER (ORDER BY LoggedDate DESC) AS RowNumber, logSource.LogSource
(SELECT COUNT(*) AS Expr1
FROM ApplicationLog ) AS TotalRecords
from ApplicationLog as appLog
left join LogSource as logSource on appLog.LogSourceId = logSource.LogSourceId
)

How to get return rowcount from stored proceedure - SQL Server 2012

I am writing a stored procedure in SQL Server 2012 and facing problem while reading the number of rows that the stored procedure will return after matching all the conditions and join criteria.
My stored procedure is:
SELECT DISTINCT
COUNT(crs.CourseId) OVER() AS Recordcounts,
crs.CourseId,
crs.CourseName,
crs.CourseDescription,
(SELECT CourseGroupName FROM CourseGroup cgrp
WHERE cgrp.CourseGroupId = crs.CourseGroupId) AS Category
FROM
Courses crs
INNER JOIN
CourseRequests creq ON crs.CourseId = creq.CourseId
WHERE
crs.Coursename <> ''''
It is returning 16 as "Recordcounts" for one of condition, but in actual, the result is 3 rows only.
Can anybody help me with this?
Thanks
Below screenshot will give more clear idea about problem for one of condition:
Try this:
;with cte as(
SELECT distinct
crs.CourseId,
crs.CourseName,
crs.CourseDescription,
(SELECT CourseGroupName FROM CourseGroup cgrp
WHERE cgrp.CourseGroupId = crs.CourseGroupId) AS Category
FROM
Courses crs
INNER JOIN
CourseRequests creq ON crs.CourseId = creq.CourseId
WHERE
crs.Coursename <> '''')
Select *, (select COUNT(CourseId) from cte) AS Recordcounts
from cte

Resources