cannot use multiple select queries in pgadmin4 - pgadmin-4

Is it that pgadmin 4 does not support the execution of multiple select queries?
I tried executing this query
select cust, prod
from sales;
select *
from sales
it only showed me one table

You are missing semicolon after first query which is incorrect SQL syntax.
select cust, prod
from sales;
select *
from sales;
FYI, do not expect two separate results after executing it in query tool, you will only get result from last query only.
Updates for WITH clause question.
with Min_cust as (
select cust, max(quant),min(quant) from sales group by cust
),
FinalMin as (
select sales.cust,sales.prod,minium from sales
natural join Min_cust as A where sales.quant=A.min
)
select * from FinalMin;

Related

Cross querys with CTE into single query (MSSQL)

Good afternoon,
I've 2 tables into my SQL DB, in the first I've the asignation for days to a person, and other the registry per day of this person, I will like see if this person have or not registry for each day into the range of specification.
I've encountered a query that uses CTE for return the range in days independent, and other query in that I've the registry group by person and day, but I can't cross these queries.
Bottom there is a picture with queries and results of each.
Thanks.
My SQL querys
You may use several CTEs in one statement, so you may put each query in separate CTE and join them later lake that:
SELECT
p.cedula, p.starttime,
r.Descr, r.Candidad
FROM ctePeriod p
LEFT JOIN cteRegistry r on r.cedula = p.cedula AND r.Dia = p.StartTime
ORDER BY p.cedula, p.starttime
all above as a single query.
Another way is to put results of your Query1 and Query2 into temp tables and build your final query on those temp tables e.g.:
SELECT DISTINCT ...
INTO #Period
FROM CTE
WHERE ...
SELECT ...
INTO #Registro
FROM Registro
GROUP BY ...
SELECT
p.cedula, p.starttime,
r.Descr, r.Candidad
FROM #Period p
LEFT JOIN #Registro r on r.cedula = p.cedula AND r.Dia = p.StartTime
ORDER BY p.cedula, p.starttime

SQL queries combined into one row

I'm having some difficulty combining the following queries, so that the results display in one row rather than in multiple rows:
SELECT value FROM dbo.parameter WHERE name='xxxxx.name'
SELECT dbo.contest.name AS Event_Name
FROM contest
INNER JOIN open_box on open_box.contest_id = contest.id
GROUP BY dbo.contest.name
SELECT COUNT(*) FROM open_option AS total_people
SELECT SUM(scanned) AS TotalScanned,SUM(number) AS Totalnumber
FROM dbo.open_box
GROUP BY contest_id
SELECT COUNT(*) FROM open AS reff
WHERE refer = 'True'
I would like to display data from the fields in each column similar to what is shown in the image below. Any help is appreciated!
Tab's solution is fine, I just wanted to show an alternative way of doing this. The following statement uses subqueries to get the information in one row:
SELECT
[xxxx.name]=(SELECT value FROM dbo.parameter WHERE name='xxxxx.name'),
[Event Name]=(SELECT dbo.contest.name
FROM contest
INNER JOIN open_box on open_box.contest_id = contest.id
GROUP BY dbo.contest.name),
[Total People]=(SELECT COUNT(*) FROM open_option),
[Total Scanned]=(SELECT SUM(scanned)
FROM dbo.open_box
GROUP BY contest_id),
[Total Number]=(SELECT SUM(number)
FROM dbo.open_box
GROUP BY contest_id),
Ref=(SELECT COUNT(*) FROM open WHERE refer = 'True');
This requires the Total Scanned and Total Number to be queried seperately.
Update: if you then want to INSERT that into another table there are essentially two ways to do that.
Create the table directly from the SELECT statement:
SELECT
-- the fields from the first query
INTO
[database_name].[schema_name].[new_table_name]; -- creates table new_table_name
Insert into a table that already exists from the INSERT
INSERT INTO [database_name].[schema_name].[existing_table_name](
-- the fields in the existing_table_name
)
SELECT
-- the fields from the first query
Just CROSS JOIN the five queries as derived tables:
SELECT * FROM (
Query1
) AS q1
CROSS JOIN (
Query2
) AS q2
CROSS JOIN (...
Assuming that each of your individual queries only returns one row, then this CROSS JOIN should result in only one row.

How to write query without "Cube" function in oracle?

I am working at ROLAP on Oracle and i have this Fact Table :
Sales(market_id,item_id,sale), and i have this query :
SELECT market_id,item_id,SUM(sale) FROM Sales
GROUP BY CUBE(market_id,item_id);
Is there another way to get the same results but without using "CUBE" function ?
Te below query is an equivalent to a query with CUBE(market_id,item_id) clause (gives the same resultset).
But it will be slower, it will read the table 4 times - CUBE is optimized, it reads the table only once.
SELECT market_id,item_id,SUM(sale)
FROM Sales
GROUP BY market_id,item_id
UNION ALL
SELECT market_id,NULL,SUM(sale)
FROM Sales
GROUP BY market_id,NULL
UNION ALL
SELECT NULL,item_id,SUM(sale) FROM Sales
GROUP BY NULL,item_id
UNION ALL
SELECT NULL, NULL,SUM(sale)
FROM Sales
GROUP BY NULL, NULL
You can also solve it by using grouping_sets From Aggregation Function
and it will give you the same result
SELECT market_id,item_id,SUM(sale) FROM Sales
Group by GROUPING SETS ( (market_id,item_id) , (market_id)(item_id), () );

SQL Server : error which works well in Oracle

I'm migrating from an Oracle database to SQL Server 2012. Some SQL which works well in Oracle doesn't work with SQL Server.
The following is my SQL and the error.
SELECT
SUM(COUNT(DISTINCT dfc.rentalNumber))
FROM
DueFromClient dfc
WHERE
dfc.facilityId=:facilityId
AND dfc.isRentalComponent = 1
GROUP BY
dfc.rentalNumber
and the error is
Cannot perform an aggregate function on an expression containing an aggregate or a subquery
Remove the SUM from the query, as it has no use, since you are also using GROUP BY. The results will be the same as your original query.
SELECT
COUNT(DISTINCT dfc.rentalNumber)
FROM DueFromClient dfc
WHERE dfc.facilityId = facilityId
AND dfc.isRentalComponent = 1
GROUP BY dfc.rentalNumber
This doesn't make much sense, so I suggest also adding the rentalNumber to the SELECT in order to make sense of your data and to also make full use of the GROUP BY.
SELECT
COUNT(DISTINCT dfc.rentalNumber)
, dfc.rentalNumber
FROM DueFromClient dfc
WHERE dfc.facilityId = facilityId
AND dfc.isRentalComponent = 1
GROUP BY dfc.rentalNumber
You don't need to sum count and group by. Try this:
SELECT
COUNT(DISTINCT dfc.rentalNumber)
FROM
DueFromClient dfc
WHERE
dfc.facilityId=:facilityId
AND dfc.isRentalComponent = 1
sqlfiddle for this query
All of proposed below are suboptimal and returns same result as query above, but they may meet needs of #Sachi Pj with using of same construction as in original query with SUM(COUNT(DISTINCT()) two more options:
SELECT SUM(dfc2.rentalNumber)
FROM
(
SELECT
COUNT(DISTINCT dfc.rentalNumber) rentalNumber
FROM
DueFromClient dfc
WHERE
dfc.facilityId=:facilityId
AND dfc.isRentalComponent = 1
) AS dfc2
GROUP BY dfc2.rentalNumber
sqlfiddle for this query
And without GROUP BY since doubles was eliminated by distinct:
SELECT SUM(dfc2.rentalNumber)
FROM
(
SELECT
COUNT(DISTINCT dfc.rentalNumber) rentalNumber
FROM
DueFromClient dfc
WHERE
dfc.facilityId=:facilityId
AND dfc.isRentalComponent = 1
) AS dfc2
sqlfiddle for this query
You can compare with your original query sqlfiddle to being sure what the results are same.

Multiple Select against one CTE

I have a CTE query filtering a table Student
Student
(
StudentId PK,
FirstName ,
LastName,
GenderId,
ExperienceId,
NationalityId,
CityId
)
Based on a lot filters (multiple cities, gender, multiple experiences (1, 2, 3), multiple nationalites), I create a CTE by using dynamic sql and joining the student table with a user defined tables (CityTable, NationalityTable,...)
After that I have to retrieve the count of student by each filter like
CityId City Count
NationalityId Nationality Count
Same thing the other filter.
Can I do something like
;With CTE(
Select
FROM Student
Inner JOIN ...
INNER JOIN ....)
SELECT CityId,City,Count(studentId)
FROm CTE
GROUP BY CityId,City
SELECT GenderId,Gender,Count
FROM CTE
GROUP BY GenderId,Gender
I want to something like what LinkedIn is doing with search(people search,job search)
http://www.linkedin.com/search/fpsearch?type=people&keywords=sales+manager&pplSearchOrigin=GLHD&pageKey=member-home
It's so fast and do the same thing.
You can not use multiple select but you can use more than one CTE like this.
WITH CTEA
AS
(
SELECT 'Coulmn1' A,'Coulmn2' B
),
CETB
AS
(
SELECT 'CoulmnX' X,'CoulmnY' Y
)
SELECT * FROM CTEA, CETB
For getting count use RowNumber and CTE some think like this.
ROW_NUMBER() OVER ( ORDER BY COLUMN NAME )AS RowNumber,
Count(1) OVER() AS TotalRecordsFound
Please let me know if you need more information on this.
Sample for your reference.
With CTE AS (
Select StudentId, S.CityId, S.GenderId
FROM Student S
Inner JOIN CITY C
ON S.CityId = C.CityId
INNER JOIN GENDER G
ON S.GenderId = G.GenderId)
,
GENDER
AS
(
SELECT GenderId
FROM CTE
GROUP BY GenderId
)
SELECT * FROM GENDER, CTE
It is not possible to get multiple result sets from a single CTE.
You can however use a table variable to cache some of the information and use it later instead of issuing the same complex query multiple times:
declare #relevantStudent table (StudentID int);
insert into #relevantStudent
select s.StudentID from Students s
join ...
where ...
-- now issue the multiple queries
select s.GenderID, count(*)
from student s
join #relevantStudent r on r.StudentID = s.StudentID
group by s.GenderID
select s.CityID, count(*)
from student s
join #relevantStudent r on r.StudentID = s.StudentID
group by s.CityID
The trick is to store only the minimum required information in the table variable.
As with any query whether this will actually improve performance vs. issuing the queries independently depends on many things (how big the table variable data set is, how complex is the query used to populate it and how complex are the subsequent joins/subselects against the table variable, etc.).
Do a UNION ALL to do multiple SELECT and concatenate the results together into one table.
;WITH CTE AS(
SELECT
FROM Student
INNER JOIN ...
INNER JOIN ....)
SELECT CityId,City,Count(studentId),NULL,NULL
FROM CTE
GROUP BY CityId,City
UNION ALL
SELECT NULL,NULL,NULL,GenderId,Gender,Count
FROM CTE
GROUP BY GenderId,Gender
Note: The NULL values above just allow the two results to have matching columns, so the results can be concatenated.
I know this is a very old question, but here's a solution I just used. I have a stored procedure that returns a PAGE of search results, and I also need it to return the total count matching the query parameters.
WITH results AS (...complicated foo here...)
SELECT results.*,
CASE
WHEN #page=0 THEN (SELECT COUNT(*) FROM results)
ELSE -1
END AS totalCount
FROM results
ORDER BY bar
OFFSET #page * #pageSize ROWS FETCH NEXT #pageSize ROWS ONLY;
With this approach, there's a small "hit" on the first results page to get the count, and for the remaining pages, I pass back "-1" to avoid the hit (I assume the number of results won't change during the user session). Even though totalCount is returned for every row of the first page of results, it's only computed once.
My CTE is doing a bunch of filtering based on stored procedure arguments, so I couldn't just move it to a view and query it twice. This approach allows avoid having to duplicate the CTE's logic just to get a count.

Resources