I am generating a report in php (mysql),
ex:
`select count(id) as tot_user from user_table
select count(id) as tot_cat from cat_table
select count(id) as tot_course from course_table`
Like this I have 12 tables.
Can i make it in single query. If i did? Process gets slow?
SELECT (
SELECT COUNT(*)
FROM user_table
) AS tot_user,
(
SELECT COUNT(*)
FROM cat_table
) AS tot_cat,
(
SELECT COUNT(*)
FROM course_table
) AS tot_course
If you use MyISAM tables, the fastest way is querying directly the stats:
select table_name, table_rows
from information_schema.tables
where
table_schema='databasename' and
table_name in ('user_table','cat_table','course_table')
If you have InnoDB you have to query with count() as the reported value in information_schema.tables is wrong.
You can certainly us the a Select Agregation statement as Postulated by Ben James, However This will result in a view with as many columns as you have tables. An alternate method may be as follows:
SELECT COUNT(user_table.id) AS TableCount,'user_table' AS TableSource FROM user_table
UNION SELECT COUNT(cat_table.id) AS TableCount,'cat_table' AS TableSource FROM cat_table
UNION SELECT COUNT(course_table.id) AS TableCount, 'course_table' AS TableSource From course_table;
The Nice thing about an approch like this is that you can explicitly write the Union statements and generate a view or create a temp table to hold values that are added consecutively from a Proc cals using variables in place of your table names. I tend to go more with the latter, but it really depends on personal preference and application. If you are sure the tables will never change, you want the data in a single row format, and you will not be adding tables. stick with Ben James' solution. Otherwise I'd advise flexibility, you can always hack a cross tab struc.
select RTRIM(A.FIELD) from SCHEMA.TABLE A where RTRIM(A.FIELD) = ('10544175A')
UNION
select RTRIM(A.FIELD) from SCHEMA.TABLE A where RTRIM(A.FIELD) = ('10328189B')
UNION
select RTRIM(A.FIELD) from SCHEMA.TABLE A where RTRIM(A.FIELD) = ('103498732H')
SELECT t1.credit,
t2.debit
FROM (SELECT Sum(c.total_amount) AS credit
FROM credit c
WHERE c.status = "a") AS t1,
(SELECT Sum(d.total_amount) AS debit
FROM debit d
WHERE d.status = "a") AS t2
I know this is an old stack but i will post this Multi-SQL select case
SELECT bp.bizid, bp.usrid, bp.website,
ROUND((SELECT SUM(rating) FROM ratings WHERE bizid=bp.bizid)/(SELECT COUNT(*) FROM ratings WHERE bizid=bp.bizid), 1) AS 'ratings',
(SELECT COUNT(*) FROM bzreviews WHERE bizid=bp.bizid) AS 'ttlreviews',
bp.phoneno, als.bizname,
(SELECT COUNT(*) FROM endorsment WHERE bizid=bp.bizid) AS 'endorses'
, als.imgname, bp.`location`, bp.`ownership`,
(SELECT COUNT(*) FROM follows WHERE bizid=bp.bizid) AS 'followers',
bp.categories, bp.openhours, bp.bizdecri FROM bizprofile AS bp
INNER JOIN alluser AS als ON bp.usrid=als.userid
WHERE als.usertype='Business'
Related
I have a table called TableA
I want my results to be like this
My code
string query = "Select Column2,Count(*) from (Select DISTINCT Column1 from TableA Group by Column2)"
I have tried a lot of solutions for apparently simple task but in vain. Been stuck from couple of hours. wish Access 2007 allow a simple Count(Distinct Column1) etc but it doesn't. Help and guidance is required.
So dbmitch comment gave me headstart, I just changed it a bit. Here is the solution:
"Select Column2,Count(T1.Column1) AS Column3 from (Select Column2,Column1 from TableA Group by Column1,Column2) AS T1 Group by T1.Column2"
Try this:
SELECT column2, Count(*) AS C FROM (SELECT DISTINCT column1 FROM TableA GROUP BY column2) AS D;
I have a MySQL table of different match record. Now I want to make result that shows the total matches, win matches and lost matches by our desire team against different teams that had played with our desire team
And I have explained my problem in a picture that is in
Try once...
select tmat.t1 as 'Team',sum(`total Match`) as `total Match`,
(select count(*) `total win` from tmatch where tmatch.w = tmat.t1) as `Total Win`,
(select count(*) `total loss` from tmatch where tmatch.l = tmat.t1) as `Total loss`
from (
SELECT t1,count(*) `total Match` from tmatch group by t1
union all
SELECT t2 ,count(*) `total Match` from tmatch group by t2) tmat group by tmat.t1
I have a question regarding joining tables.
I have eleven tables, one parent with ten child tables. Primary key on all is EventName with the relationship from parent to child being EventName as well. The child tables names are SR1Laptimes, SR2Laptimes etc x 10.
The schema in the child tables are identical. I'm trying to join Events table to SR1Laptimes and then Union all the child table together but can't get it to work.
There is a method behind this madness but would take some time to explain. Here's the code anyway, any feed back would be greatly appreciated. P.S the codes not finished in this copy and paste.
myCommand.CommandText = "SELECT MIN(Q1), MIN(Q2), MIN(Q3), MIN(Q4), MIN(LaptimesMinutes), MIN(LaptimesSeconds) FROM Events LEFT JOIN SR1Laptimes ON Events.EventName = SR1Laptimes.EventName SELECT * FROM SR1Laptimes UNION ALL SELECT * FROM SR2Laptimes UNION ALL SELECT * FROM SR3Laptimes WHERE (Events.Track = #track) AND (Events.Number = #number) AND (Events.Rider = #rider)";
myCommand.Parameters.AddWithValue("#track", analysisTrackComboBox.Text);
myCommand.Parameters.AddWithValue("#number", analysisNumberComboBox.Text);
myCommand.Parameters.AddWithValue("#rider", analysisRiderComboBox.Text);
I think you are missing an UNION ALL clause at:
... ON Events.EventName = SR1Laptimes.EventName *HERE* SELECT * FROM SR1Laptimes ...
Are the tables you try to 'union all' have same columns? That might be the problem.
And 'where' clause at the end is valid only for SR3Laptimes.
This example may help you.
DECLARE #Parent TABLE (id INT,sth NVARCHAR(100))
DECLARE #ChildTest1 TABLE(id INT,parentId INT, sth NVARCHAR(100))
DECLARE #ChildTest2 TABLE(id INT, parentId INT, sth NVARCHAR(100))
INSERT INTO #Parent
SELECT 1,'Ali'
UNION ALL
SELECT 2,'Veli'
UNION ALL
SELECT 3,'Ahmet'
INSERT INTO #ChildTest1
SELECT 1,1,'Parent1_Child1_1strow'
UNION ALL
SELECT 2,1,'Parent1_Child1_2ndrow'
UNION ALL
SELECT 3,2,'Parent2_Child1_1strow'
INSERT INTO #ChildTest2
SELECT 1,1,'Parent1_Child2_1strow'
UNION ALL
SELECT 2,2,'Parent2_Child2_1strow'
UNION ALL
SELECT 3,3,'Parent3_Child2_1strow'
SELECT * FROM #Parent p
LEFT JOIN (
SELECT * FROM #ChildTest1 ct1
UNION ALL
SELECT * FROM #ChildTest2 ct2
) s ON p.id =s.parentId
--WHERE p.id = 3
I want to create a statement like the following:
if (select statement1 returns rows){
select statement2
}
else {
select statement3
}
This if statement is part of a bigger query
select from products where p.id in (
if (select statement1 returns rows){
select statement2
}
else {
select statement3
}
Is this possible in SQL Server, or is my thinking incorrect?
You need to use a combination of EXISTS and CASE..END:
select *
from products
where p.id in (
case when (exists ( <statement1> ))
then ( <statement2> )
else ( <statement3> )
end
)
Where <statement1> might be: SELECT * FROM Customer WHERE Id = 123
<statement2> might be: SELECT MIN(field) FROM someTable
<statement3> might be: SELECT 0 as DefaultValue
If you can show some examples of what you want those actual statements to be I can provide a more concrete answer.
Actually SQL is more rigid, due to performance considerations. Your query will look more like this:
select *
from products
where 1 = case when (exists ( <statement1> ))
then case when p.id in ( <statement2> ) then 1 else 0 end
else case when p.id in ( <statement3> ) then 1 else 0 end
end
Since you are checking for the same id existance, I think you could do a UNION here.
select *
from products
where p.id in (select id from table1
union
select id from table2)
I'd recommend using a UNION between your two conditions to help avoid performance problems...and may be easier to read as well.
SELECT FROM products p
WHERE EXISTS (SELECT STATEMENT1)
AND EXISTS (SELECT STATEMENT2 s2 WHERE s2.p_id = p.id)
UNION
SELECT FROM products p
WHERE NOT EXISTS (SELECT STATEMENT1)
AND EXISTS (SELECT STATEMENT3 s3 WHERE s3.p_id = p.id)
Depending on the nature of the statements, you might be able to leave off the Not Exists in the second select.
I have 2 tables:
First (Cases)
Second (Comments)
in one to many relation ; I'm storing the comments of each case in Comments table.
I need to select case information from Cases table which are presented in Comments table, but I want each case to be displayed ONCE ordered by comments added date (cDate)
I tried:
SELECT TOP 10
Cases.*,
comments.cDate
FROM
Cases
INNER JOIN comments
ON Cases.Case_ID = comments.Case_ID
WHERE comments.Case_ID IN
(
SELECT DISTINCT
Case_ID
FROM
comments
)
ORDER BY cDate DESC
but its retrieving the case multiple times if it has many comments. I need it to appear one time only
Thank you all, you helped alot ,,
I just added
Cases.Case_ID IN (SELECT Case_ID FROM comments)
and it worked perfectly.
Select statement is like this now:
SELECT top 10 Cases.*,
(SELECT MAX(comments.cDate)
FROM comments
WHERE Cases.Case_ID = comments.Case_ID ) AS cDate
FROM Cases
WHERE Cases.Case_ID
IN (SELECT Case_ID FROM comments)
ORDER BY cDate DESC
Thanks once again :)
In this case, it looks like you want to use a subquery:
SELECT top 10 Cases.*,
(SELECT MAX(comments.cDate) FROM comments
WHERE Cases.Case_ID = comments.Case_ID ) AS cDate
FROM Cases
ORDER BY cDate DESC
This will do:
SELECT TOP 10
A.* ,
(SELECT MAX(C.cDate) FROM comments C WHERE C.Case_ID = A.Case_ID) commDate
FROM Cases A
INNER JOIN comments B ON A.Case_ID = B.Case_ID
ORDER BY commDate
(#yhw42 query will return Cases which have no comments as well.)
First some test data:
DECLARE #tblCases TABLE(Case_ID INT)
DECLARE #comments TABLE(Case_ID INT,cDate DATETIME)
INSERT INTO #tblCases
SELECT 1 UNION ALL SELECT 2
INSERT INTO #comments
SELECT 1,GETDATE() UNION ALL
SELECT 1,GETDATE()-1 UNION ALL
SELECT 2,GETDATE()-2 UNION ALL
SELECT 2,GETDATE()-3
Then i would do it like this.
;WITH CTE AS
(
SELECT
RANK() OVER(PARTITION BY Case_ID ORDER BY cDate DESC) AS iRank,
tbl.cDate,
tbl.Case_ID
FROM
#comments AS tbl
)
SELECT TOP 10
Cases.*,
CTE.cDate
FROM
CTE
JOIN #tblCases AS Cases
ON Cases.Case_ID=CTE.Case_ID
WHERE
CTE.iRank=1
Thank you all, you helped alot ,, I just added
Cases.Case_ID IN (SELECT Case_ID FROM comments)
and it worked perfectly.
Select statement is like this now:
SELECT top 10 Cases.*,
(SELECT MAX(comments.cDate)
FROM comments
WHERE Cases.Case_ID = comments.Case_ID ) AS cDate
FROM Cases
WHERE Cases.Case_ID
IN (SELECT Case_ID FROM comments)
ORDER BY cDate DESC
Thanks once again :)