繁体   English   中英

将多个SQL计数到单个结果集中

[英]Multiple SQL counts into single result set

大家好

我正在尝试做一些我认为在MYSQL上不可能的事情。

我们有一个非常大的数据库,可从中提取所创建产品的生产报告。 目前,我们运行多个查询以获取这些结果,然后在将数据发送给需要报告的人之前,将数据手动传输到表中。

有没有更简单的方法可以做到这一点。 IE浏览器一个查询。

我运行的查询示例

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>";

我正在寻找结果的示例

  1. 产品A产品B产品C
  2. 500 500 500

您可以将所有内容放入Select子句中,如下所示:

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

这样,您将获得如下输入:

  • CountA CountB CountC
  • 500 500 500

您以后可以轻松添加更多计数

您可以使用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>";

当然,您可以仅选择其他4种产品的选择或任何您想要的数量;-)

我认为您需要使用存储过程

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

谢谢,塔哈

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM