我想使用以下逻辑编写查询:
我有一个项目表,其中所有交易都按不同的站点位置和营业日期存储,我还为每个存储的订单都有一个密钥。现在,我的项目表如下:
SiteID BusinessDate ItemName Units Sold Units Sale ItemNo OrderNo
----------------------------------------------------------------------------
1 06/08/2018 Apple 1 5 10001 122-1
1 06/08/2018 Coffee 1 16 10002 122-1
1 06/08/2018 Bread 2 7 10003 122-1
1 06/08/2018 Beans 9 18 10004 122-1
1 06/08/2018 Apple 2 5 10001 122-4
1 06/08/2018 Coffee 2 6 10002 122-4
1 06/08/2018 Bread 1 7 10003 122-4
1 06/08/2018 Beans 4 8 10004 122-4
2 06/08/2018 Apple 2 5 10001 122-2
2 06/08/2018 Coffee 1 6 10002 122-2
3 06/08/2018 Bread 3 5 10003 122-3
3 06/08/2018 Beans 7 17 10004 122-3
现在,我想获取输出,如果用户选择的基本商品为“ 10001”,那么它应计算与该订单一起出售的所有商品的已售出单位价值,但不包括基本商品本身情况是“ 10001”
所以最终输出应如下所示:
SiteID BusinessDate Item Code Itemname Units Sold Units Sale
----------------------------------------------------------------------------
1 06/08/2018 10001 Apple 3 62
2 06/08/2018 10001 Apple 2 6
3 06/08/2018 10001 Apple 0 0
售出单位=我的基本商品的总单位,siteID = 1上的“ 10001”
单位销售额=与我的基本商品一起购买的所有其他商品的总单位销售额,不包括我的基本商品的单位销售价值。
答案 0 :(得分:0)
一种方法是使用CROSS APPLY
和OUTER APPLY
。如果您在结果集中不需要SiteID 3,则可以稍微简化一下。
DECLARE @itemNo INT
SET @itemNo = 10001
SELECT tmp.*, ca.*, oa.UnitsSold, CASE WHEN oa.UnitsSold = 0 THEN 0 ELSE oa.UnitsSale END AS UnitsSale
FROM (SELECT DISTINCT SiteID, BusinessDate FROM YourTable) tmp
CROSS APPLY (SELECT DISTINCT ItemNo, ItemName FROM YourTable WHERE ItemNo = @itemNo) ca
OUTER APPLY (SELECT SUM(CASE WHEN ItemNo = @itemNo THEN [Units Sold] ELSE 0 END) AS UnitsSold,
SUM(CASE WHEN ItemNo != @itemNo THEN [Units Sale] ELSE 0 END) AS UnitsSale
FROM YourTable
WHERE SiteID = tmp.SiteID AND BusinessDate = tmp.BusinessDate) oa
答案 1 :(得分:-1)
尝试一下
Select SiteID,BusinessDate,ItemNo,MAX(Itemname) AS Itemname,SUM(Units Sold) As Units Sold,SUM(Units Sale) As Units Sale
Group By SiteID, BusinessDate, ItemNo