子查询where

时间:2018-06-15 04:22:47

标签: sql sql-server reporting-services

您好我在查询中无法生成正确的结果。实质上。我认为吨销售部分是正确的,但我收到的已发货不是值的值不是。

它们基本上是相同的查询,但子查询应该查找仅设置为已交付的值。我显示的值可能相同或更少。

它们将按颜色代码(完成ID)

进行分组

这些是我得到的结果

enter image description here

 SELECT id.[Color Code] as FinishID
        ,sum((fso.[SO Quantity] * (isnull(dp.[Net Weight], 0) * isnull(dp.[Length], 0))) * 0.001) as TonnesSold  

        ,(select sum((fso2.[SO Quantity] * (isnull(dp2.[Net Weight], 0) * isnull(dp2.[Length], 0))) * 0.001)
            --count([sales order key]) 
            from [dbo].[FactSalesOrders] fso2
            JOIN [dbo].[DimInventoryDimension] id2 on fso2.[Inventory Dimension Key] = id2.[Inventory Dimension Key]
            JOIN [dbo].[DimProduct] dp2 on dp2.[Product Key] = fso2.[Product Key]
            where fso.[Shipping Date] between @StartDate and @EndDate
            OR
            (fso2.[Shipping Date] in (SELECT [DateKey]          
             FROM [dbo].[DimDate] where [Month Order] = @Month))
            and 
            fso2.[sales status] = 'Delivered' 
            and id2.[Color Code] = id.[Color Code] 
            AND dp2.[Coverage Group Code] like 'EXT%') as ShippedNotInv

FROM [dbo].[FactSalesOrders] fso
JOIN [dbo].[DimInventoryDimension] id on fso.[Inventory Dimension Key] = id.[Inventory Dimension Key]
JOIN [dbo].[DimProduct] dp on dp.[Product Key] = fso.[Product Key]

WHERE (fso.[Shipping Date] between @StartDate and @EndDate )
OR
(fso.[Shipping Date] in (SELECT [DateKey]          
  FROM [dbo].[DimDate] where [Month Order] = @Month))
AND dp.[Coverage Group Code] like 'EXT%'

GROUP BY id.[Color Code]--, fso.[Sales Status]

提前感谢:)获取任何帮助

1 个答案:

答案 0 :(得分:1)

    ;WITH CTC
    AS
    (
        SELECT id.[Color Code] as FinishID, fso.[SO Quantity], dp.[Net Weight], dp.[Length], fso.[sales status]
        FROM [dbo].[FactSalesOrders] fso
        JOIN [dbo].[DimInventoryDimension] id on fso.[Inventory Dimension Key] = id.[Inventory Dimension Key]
        JOIN [dbo].[DimProduct] dp on dp.[Product Key] = fso.[Product Key]
        WHERE (fso.[Shipping Date] between @StartDate and @EndDate )
        OR
        (
            fso.[Shipping Date] in 
            (SELECT [DateKey] FROM [dbo].[DimDate] where [Month Order] = @Month)
        )
        AND dp.[Coverage Group Code] like 'EXT%'
    )
    SELECT c.FinishID, 
    (SELECT SUM((t.[SO Quantity] * (isnull(t.[Net Weight], 0) * isnull(t.[Length], 0))) * 0.001) 
FROM CTC t GROUP BY t.FinishID HAVING t.FinishID = c.FinishID) as TonnesSold,
    (SELECT SUM((t.[SO Quantity] * (isnull(t.[Net Weight], 0) * isnull(t.[Length], 0))) * 0.001) 
FROM CTC t WHERE t.[sales status] = 'Delivered' GROUP BY t.FinishID HAVING t.FinishID = c.FinishID) as ShippedNotInv 
    FROM CTC c GROUP BY c.FinishID