从子查询中提取费用字段

时间:2018-12-18 19:22:39

标签: sql azure-sql-database

我编写了以下查询,以将单位成本从另一个表COSreport中提取到我的获利能力查询ProfitabilityReport中,但子查询存在问题。

select 
i.tranid
, it.item_id
, it.displayname
, tl.Item_Count * -1 Unit_Qty
, case when tl.Item_Count=0 then 0 
         else ((tl.GROSS_AMOUNT * -1)/ Item_Count) * -1 
end as PricePerUnit,

**(select sum(c.tranamt) from ns.COSreport c
  inner join ns.ProfitabilityReport d
  on c.InvoiceID = d.tranid 
and c.item_id = d.item_id) as 'True Cost'**

, '0' 'Cost Per M'

from ns.tinvoice i
join ns.transaction_lines tl on i.transaction_id = tl.transaction_id
join ns.Customers cust on c.customer_id = i.ENTITY_ID
join ns.items it on it.item_id = tl.item_id
left join ns.ITEM_CLASSIFICATION it_class on it_class.list_id = 
it.ITEM_CLASSIFICATION_ID
where list_item_name IS NOT NULL
and i.tranid = '1262INV'

我同时加入了invoice iditem id,以便从COSReport获得给定发票和项目的适当费用。

但是,真实成本不是与单位成本相乘,而是对整个表的成本字段求和。

例如,使用下面查询中指定的发票号1262INV参见以下内容。费用应分别为1.04、0.26和4,而费用为138m。

enter image description here

任何帮助您解决此问题的人将不胜感激

2 个答案:

答案 0 :(得分:1)

我实际上更喜欢使用CTE来提高可读性。您可以将子查询放入CTE中,然后将其加入主查询中,但是您需要将traniditem_id字段添加到CTE中,以便可以在您的加入。

编辑:由于您使用的是Azure SQL Server,因此在WITH之前不需要分号。

WITH TrueCosts AS
(
    SELECT
        d.tranid 
        ,d.item_id
        ,TrueCost = SUM(c.tranamt) 
    FROM ns.COSreport c
    INNER JOIN ns.ProfitabilityReport d
        ON c.InvoiceID = d.tranid 
            AND c.item_id = d.item_id
    GROUP BY d.tranid 
        ,d.item_id
)
SELECT 
    i.tranid
    , it.item_id
    , it.displayname
    , tl.Item_Count * -1 Unit_Qty
    , case when tl.Item_Count=0 then 0 
             else ((tl.GROSS_AMOUNT * -1)/ Item_Count) * -1 
        END as PricePerUnit
    , tc.TrueCost AS 'True Cost'
    , '0' AS 'Cost Per M'
FROM ns.tinvoice i
JOIN ns.transaction_lines tl on i.transaction_id = tl.transaction_id
JOIN ns.Customers c on c.customer_id = i.ENTITY_ID
JOIN ns.items it on it.item_id = tl.item_id
LEFT JOIN ns.ITEM_CLASSIFICATION it_class on it_class.list_id = it.ITEM_CLASSIFICATION_ID
LEFT JOIN TrueCosts tc ON tc.tranid = i.tranid AND tc.item_id = tl.item_id
WHERE list_item_name IS NOT NULL
    AND i.tranid = '1262INV'

答案 1 :(得分:0)

您有几个问题。

在子查询中,purrr使用别名library(data.table) library(dplyr) library(tidyr) library(purrr) # Create some sample data set.seed(1) dt <- data.table(site = sample(1:6, 50, replace=T), space = sample(1:4, 50, replace=T), measure = sample(c('cfl', 'led', 'linear', 'exit'), 50, replace=T), qty = round(runif(50) * 30), qty.exit = 0, delta.watts = sample(10.5:100.5, 50, replace=T), cf = runif(50)) dt2 <- dt %>% nest(-measure) %>% mutate(data = if_else( measure == "exit", map(data, function(x) mutate(x, qty.exit = qty, cf = 0, delta.watts = 13)), data )) %>% unnest() 。您还可以在外部查询中为c使用别名COSReport

更大的问题是您的子查询与外部查询根本不相关。这就是为什么要汇总整个表。

要关联子查询,您需要(在子查询中)联接到外部查询中的表之一。不确定您的表或数据,但是我猜想您会在子查询的WHERE子句中使用c