加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

sql-server – 如何在存储过程中将两个查询联合起来以获得一行结

发布时间:2020-12-12 06:33:51 所属栏目:MsSql教程 来源:网络整理
导读:我有一个存储过程,我加入了两个查询.我的疑问是 alter PROCEDURE test@SDate datetime,@EDate datetime 如 -- SET NOCOUNT ON added to prevent extra result sets from-- interfering with SELECT statements.SET NOCOUNT ON;-- Insert statements for proce
我有一个存储过程,我加入了两个查询.我的疑问是
alter PROCEDURE test

@SDate datetime,@EDate datetime

-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

-- Insert statements for procedure here
(Select count(quoteid) as TotalQuote,sum(totalamount) as QuoteAmount from dbo.QuoteBase
where CreatedOn BETWEEN @SDate AND @EDate) 
union All

(select  count(salesorderid)as TotalOrders,sum(totalamount) as OrderAmount from dbo.SalesOrderBase Where
CreatedOn BETWEEN @SDate AND @EDate)

我得到了结果列

Total Quote    Quote Amount
17                   700
118                 5000

但我想要结果

Total Quote    Quote Amount    Total Orders   Order Amount
  17               700              118           5000

如果有人有想法请与我分享

解决方法

试试这个 –
ALTER PROCEDURE dbo.usp_test

      @SDate DATETIME,@EDate DATETIME

AS BEGIN

    SET NOCOUNT ON;

    SELECT 
          t.TotalQuote,t.QuoteAmount,t2.TotalOrders,t2.OrderAmount
    FROM (SELECT a = 1) a
    CROSS JOIN (
        SELECT 
              TotalQuote = COUNT(quoteid),QuoteAmount = SUM(totalamount)
        FROM dbo.QuoteBase
        WHERE CreatedOn BETWEEN @SDate AND @EDate
    ) t
    CROSS JOIN (
        SELECT 
              TotalOrders = COUNT(salesorderid),OrderAmount = SUM(totalamount) 
        FROM dbo.SalesOrderBase
        WHERE CreatedOn BETWEEN @SDate AND @EDate
    ) t2

END

更新:

SELECT 
      t.TotalQuote,t2.OrderAmount
FROM (
    SELECT 
          TotalQuote = COUNT(quoteid),QuoteAmount = SUM(totalamount)
    FROM dbo.QuoteBase
    WHERE CreatedOn BETWEEN @SDate AND @EDate
) t
FULL OUTER JOIN
(
    SELECT 
          TotalOrders = COUNT(salesorderid),OrderAmount = SUM(totalamount) 
    FROM dbo.SalesOrderBase
    WHERE CreatedOn BETWEEN @SDate AND @EDate
) t2 ON 1 = 1

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读