Frage

Howsit everyone

I am trying to do something i think is impossible on MYSQL.

We have a very large database where we pull production reports from for our products created. At the moment we run multiple queries to get these results and then transfer the data manually to a table before it gets sent off to whomever needs the reports.

is there an easier way to do this. IE a single query.

Examples of the queries i run

a. SELECT count(id) from ProductA_T where created between '<date>' and '<date>' and productstatus = "<successful>";
b. SELECT count(id) from ProductB_T where created between '<date>' and '<date>' and productstatus = "<successful>";
c. SELECT count(id) from ProductC_T where created between '<date>' and '<date>' and productstatus = "<successful>";

Example of the result im looking for

  1. ProductA ProductB ProductC
  2. 500 500 500
War es hilfreich?

Lösung

You can put everything into a Select clause, like this:

Select
(SELECT count(id) from ProductA_T where created between '<date>' and '<date>' and productstatus = "<successful>") as CountA
(SELECT count(id) from ProductB_T where created between '<date>' and '<date>' and productstatus = "<successful>") as CountB
(SELECT count(id) from ProductC_T where created between '<date>' and '<date>' and productstatus = "<successful>") as CountC

That way you'll have an input like this:

  • CountA CountB CountC
  • 500 500 500

You can later add more Count easily

Andere Tipps

You could use UNION ALL:

SELECT 'ProductA', count(id) from ProductA_T where created between '<date>' and '<date>' and productstatus = "<successful>"
UNION ALL
SELECT 'ProductB', count(id) from ProductB_T where created between '<date>' and '<date>' and productstatus = "<successful>"
UNION ALL
SELECT 'ProductC', count(id) from ProductC_T where created between '<date>' and '<date>' and productstatus = "<successful>";

Of course, you can just duplicate the select for other 4 products or any amount you wish ;-)

I think you need to use Stored Procedure

Create StoredProcedure SP_Name_1
As
Beign
Declare @id1 int,@id2 int,@id3 int;
SELECT @id1 = count(id) from ProductA_T where created between '<date>' and '<date>' and productstatus = "<successful>";
SELECT @id2 = count(id) from ProductB_T where created between '<date>' and '<date>' and productstatus = "<successful>";
SELECT @id2 = count(id) from ProductC_T where created between '<date>' and '<date>' and productstatus = "<successful>";

select  @id1 as ProductA ,@id2 as ProductB ,@id3 as ProductC
End

Thanks, Taha

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top