【问题标题】:How to combine two select query results into one result using sp?如何使用sp将两个select查询结果合并为一个结果?
【发布时间】:2016-09-27 23:01:05
【问题描述】:

我要声明两个比较日期,我想要两个日期的数据。我使用left join 进行组合提议,但这不是正确的方法。我缺少一些数据。而不是左连接,哪个最适合?

结果

productid   FirstQty    SecondQty   FirstProductRevenue SecondProductRevenue

COCAK117    1             2          1370.00              1440.00
COCAK632    1             2          1125.00              2250.00
COCAK656    1             NULL        795.00               NULL
COCAK657    1             2           720.00              2090.00
COCAK775    3             1           2475.00             825.00

我从第一个表中获取数据并从第二个表中获取匹配的 productid,但我想要两个表中的总 productid。

CREATE PROCEDURE [dbo].[Orders]    
(        
     @StartDate     DATETIME,        
     @EndDate       DATETIME,
     @StartDate1    DATETIME,        
     @EndDate1      DATETIME,
     @Rowname       VARCHAR(100), 
     @AssociateName VARCHAR(50)         
)
--[Orders] '05/03/2015','05/03/2015','05/05/2015','05/07/2015','Most Gifted Cakes','all'
AS BEGIN 
 if(@AssociateName='all')
BEGIN
        ----First duration for all associates-----

select t1.productid,t1.FirstQty,t2.SecondQty,t1.FirstProductRevenue,t2.SecondProductRevenue 
from 
(select op.Productid
      , count(op.ProductId)as FirstQty
      , Round(Sum(op.Price*op.Quantity),0) as FirstProductRevenue 
 from Orderdetails od 
 inner join (select Distinct Orderid,productid,Price,Quantity from Orderproducts)  op on op.Orderid=od.Orderid 
 inner JOIN City ct  ON od.RecipientCityName = ct.CityName 
 INNER JOIN Associates ass ON Ct.AssociateId = ass.AssociateId
 Inner join HomepageRowWiseProducts hr on op.ProductId=hr.Productid 
 where  Convert(datetime,Convert(Varchar(50),od.DeliveryDate,101)) between @StartDate and @EndDate 
   and (od.TransactionId IS NOT NULL or ltrim(od.TransactionId) !=  '') 
   and @Rowname=hr.HomepageRow_name and hr.status=1 
   Group by op.Productid
) t1
   ----Second duration for all associates-----
left join 
 (select op.Productid
       , count(op.ProductId)as SecondQty
       , Round(Sum(op.Price*op.Quantity),0) as SecondProductRevenue 
 from Orderdetails od 
 inner join (select Distinct Orderid,productid,Price,Quantity from Orderproducts)  op on op.Orderid=od.Orderid 
 inner JOIN City ct  ON od.RecipientCityName = ct.CityName 
 INNER JOIN Associates ass ON Ct.AssociateId = ass.AssociateId
 Inner join HomepageRowWiseProducts hr on op.ProductId=hr.Productid 
 where  Convert(datetime,Convert(Varchar(50),od.DeliveryDate,101)) between @StartDate1 and @EndDate1 
   and (od.TransactionId IS NOT NULL or ltrim(od.TransactionId) !=  '') 
   and @Rowname=hr.HomepageRow_name and hr.status=1
   Group by op.Productid
) t2 on t1.productid=t2.productid
END

【问题讨论】:

  • 你不能使用 UNION ALL 吗?我相信这会给你想要的结果
  • 没有联合是不可能的我也想要比较日期
  • 在选择中我提到了 firstQty 的意思(从 '05/03/2015' 到 '05/03/2015'), secondQty 的意思是(从 05/05/2015' 到 '05/07/2015' ' 所以联合都是不可能的..
  • 也许 CROSS join 是您需要的,然后将所有 ProductId 插入临时表并将其加入您的结果
  • 对查询使用全外连接,对产品 ID 使用 coalesce(),第一个查询中不存在。

标签: sql sql-server join stored-procedures left-join


【解决方案1】:

您可以尝试一次获取所有数据,然后仅对所需的日期范围求和。 我可能会在这里犯一些错误,因为我没有你的数据结构。 但是,您应该知道如何实现它。

select op.Productid
       , sum(  case when Convert(datetime,Convert(Varchar(50),od.DeliveryDate,101)) between @StartDate and @EndDate then 
          1 else 0 end) FirstQty
       , sum(  case when Convert(datetime,Convert(Varchar(50),od.DeliveryDate,101)) between @StartDate1 and @EndDate1 then 
          1 else 0 end)  SecondQty,
       , Round(Sum( case when Convert(datetime,Convert(Varchar(50),od.DeliveryDate,101)) between @StartDate and @EndDate 
                        then op.Price*op.Quantity 
                         else 0 end),0) as FirstProductRevenue 
       , Round(Sum( case when Convert(datetime,Convert(Varchar(50),od.DeliveryDate,101)) between @StartDate1 and @EndDate1 
                        then op.Price*op.Quantity 
                         else 0 end),0) as SecondProductRevenue 
 from Orderdetails od 
 inner join (select Distinct Orderid,productid,Price,Quantity from Orderproducts)  op on op.Orderid=od.Orderid 
 inner JOIN City ct  ON od.RecipientCityName = ct.CityName 
 INNER JOIN Associates ass ON Ct.AssociateId = ass.AssociateId
 Inner join HomepageRowWiseProducts hr on op.ProductId=hr.Productid 
 where  ( Convert(datetime,Convert(Varchar(50),od.DeliveryDate,101)) between @StartDate and @EndDate 
       Or Convert(datetime,Convert(Varchar(50),od.DeliveryDate,101)) between @StartDate1 and @EndDate1 )
   and (od.TransactionId IS NOT NULL or ltrim(od.TransactionId) !=  '') 
   and @Rowname=hr.HomepageRow_name and hr.status=1
   Group by op.Productid

【讨论】:

  • 小疑问.. sum(当在 StartDate 和 EndDate 之间转换 (datetime,Convert(Varchar(50),od.DeliveryDate,101)) 然后 1 else 0 end) 请解释一下..我一点也不明白... @dcieslak
  • 当您的日期在该范围内时,您将总金额加 1,否则您将总金额加 0..
  • 在我的查询中我使用 count(op.Productid) 但你使用 sum(------) 但有什么区别???
  • 非常感谢......它的工作......@dcieslak
【解决方案2】:

也许这样(简化):

select coalesce(t1.productid, t2.productid) as productid, t1.FirstQty, t2.SecondQty, t1.FirstProductRevenue, t2.SecondProductRevenue 
from 
(select ...) t1
   ----Second duration for all associates-----
full join 
(select ...) t2 on t1.productid = t2.productid

【讨论】:

    【解决方案3】:

    试试这个

    你创建一个函数如下

    CREATE FUNCTION OrderDetails (
    @StartDate     DATETIME,
    @EndDate       DATETIME
    )
    RETURNS  @tblList TABLE  
    (  
    orderId  VARCHAR(1000) 
    
    )   
    AS 
    BEGIN       
     select orderid
     insert into @tblList
      from Orderdetails od inner JOIN City ct  ON od.RecipientCityName = ct.CityName  
         INNER JOIN Associates ass ON Ct.AssociateId = ass.AssociateId
     Inner join HomepageRowWiseProducts hr on op.ProductId=hr.Productid 
    
       and (od.TransactionId IS NOT NULL or ltrim(od.TransactionId) !=  '') 
       and @Rowname=hr.HomepageRow_name and hr.status=1 
      where  Convert(datetime,Convert(Varchar(50),od.DeliveryDate,101)) between @StartDate and @EndDate 
    return
    end
    

    然后根据您传递的日期调用存储过程中的函数,您不会错过任何记录

    CREATE PROCEDURE [dbo].[Orders]    
    (        
         @StartDate     DATETIME,        
         @EndDate       DATETIME,
         @StartDate1    DATETIME,        
         @EndDate1      DATETIME,
         @Rowname       VARCHAR(100), 
         @AssociateName VARCHAR(50)         
    )
    --[Orders] '05/03/2015','05/03/2015','05/05/2015','05/07/2015','Most Gifted Cakes','all'
    AS BEGIN 
     if(@AssociateName='all')
    BEGIN
            ----First duration for all associates-----
    
    select op1.Productid
          , count(op.ProductId)as FirstQty
          ,count(op1.ProductId)as SecondQty
          , Round(Sum(op.Price*op.Quantity),0) as FirstProductRevenue 
              , Round(Sum(op1.Price*op1.Quantity),0) as FirstProductRevenue 
     from (select Distinct Orderid,productid,Price,Quantity from Orderproducts opp  inner join [Your_ScemaName].[OrderDetails](@StartDate,@EndDate) od on opp.Orderid=od.Orderid  ) op 
     inner join  (select Distinct Orderid,productid,Price,Quantity from Orderproducts  opp inner join [Your_ScemaName].[OrderDetails](@StartDate1,@EndDate1) od on opp.Orderid=od.Orderid  ) op1 
    -- since 1=1 is always true you will get all data
     on 1=1
       Group by op.Productid
    end
    end
    

    【讨论】:

    • @Nithia Shanmugananthan 在这里我遇到了这样的错误 Error 为不是函数的对象“Orderdetails”提供的参数。如果参数旨在作为表提示,则需要 WITH 关键字。
    • 函数应该首先被创建。并且您应该使用模式名称调用函数。检查我编辑的答案
    猜你喜欢
    • 1970-01-01
    • 2013-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    相关资源
    最近更新 更多