【发布时间】: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