具有两列总和的子查询

时间:2018-01-04 04:45:49

标签: sql-server

你可以请你使用子查询,它给了我一个错误子查询返回 超过1个值且不允许。 当我运行它独立于它工作的较大代码时,我猜它是选择distinct或者group by子句仅使用distinct,但是当我将它添加到union时它不起作用。我有A列和B列,我想将它们加在一起给我一个总列

A栏和B栏

column A and B

    SELECT 
    T2.GL_Batchno AS BatchNo,
    T2.Creditor_Code AS ID,
    T2.Type AS TYPE,
    cast(T2.PO_Number as varchar(25)) as 'PO Number',
    T1.TranID as Invoice,
    t1.Item_GL_Code as ItemCode,
    t1.Description,
    t1.Quantity,
    t1.Price as Value,
    t1.GST as Tax,
    t1.Price_inclGST as 'Value Inc Tax',
    T2.PeriodNo AS PeriodNo,
    T2.DatePosted,
    T2.UserPosted


    FROM (CRD_InvoiceDetails AS T1
    LEFT JOIN CRD_InvoiceMast AS T2 ON T1.TranId = T2.TranID)

    UNION

    SELECT
    T2.GLBatch AS BatchNo,
    T2.CustCode AS ID,
    CASE WHEN T2.JobType = 1 THEN 'INTERNAL'
         WHEN T2.JobType = 2 THEN 'EXTERNAL'
         WHEN T2.JobType = 3 THEN 'CAPITAL PREP'
         ELSE 'OTHER' END AS TYPE,
    cast(T1.PONo as varchar(25)) as 'PO Number',
    T1.JobCode AS INVOICE,
    T1.Part_No AS ITEMCODE,
    T1.fld_Desc AS DESCRIPTION,
    t1.Qty as Quantity,
    T1.LineTotal AS Value,
    t1.lineGST as Tax,
    **(select sum(t1.LineTotal + t1.lineGST) FROM (FLEET_JOB_JobDetails AS t1
    LEFT JOIN FLEET_JOB_JobMaster AS t2 ON T1.JobCode = T2.JobCode) Group by 
     T2.GLBatch) as 'Value Inc Tax',**
    t2.PeriodPosted as PeriodNo,
    t2.DatePosted,
    t2.UserPosted
    FROM (FLEET_JOB_JobDetails AS t1
    LEFT JOIN FLEET_JOB_JobMaster AS t2 ON T1.JobCode = T2.JobCode)

2 个答案:

答案 0 :(得分:0)

您在第二个语句中有一个子查询,该子查询与外部查询没有关联,因为您将其与外部查询相同。我不清楚你要在那里实现什么,但是如果你需要通过T2.GLBatch来总结总成本,我认为更好的方法是在分区上进行SUM,这完全避免了子查询问题。

SELECT 
T2.GL_Batchno AS BatchNo,
T2.Creditor_Code AS ID,
T2.Type AS TYPE,
cast(T2.PO_Number as varchar(25)) as 'PO Number',
T1.TranID as Invoice,
t1.Item_GL_Code as ItemCode,
t1.Description,
t1.Quantity,
t1.Price as Value,
t1.GST as Tax,
t1.Price_inclGST as 'Value Inc Tax',
T2.PeriodNo AS PeriodNo,
T2.DatePosted,
T2.UserPosted


FROM (CRD_InvoiceDetails AS T1
LEFT JOIN CRD_InvoiceMast AS T2 ON T1.TranId = T2.TranID)

UNION

SELECT
T2.GLBatch AS BatchNo,
T2.CustCode AS ID,
CASE WHEN T2.JobType = 1 THEN 'INTERNAL'
     WHEN T2.JobType = 2 THEN 'EXTERNAL'
     WHEN T2.JobType = 3 THEN 'CAPITAL PREP'
     ELSE 'OTHER' END AS TYPE,
cast(T1.PONo as varchar(25)) as 'PO Number',
T1.JobCode AS INVOICE,
T1.Part_No AS ITEMCODE,
T1.fld_Desc AS DESCRIPTION,
t1.Qty as Quantity,
T1.LineTotal AS Value,
t1.lineGST as Tax,
sum(t1.LineTotal + t1.lineGST) OVER (PARTITION BY T2.GLBatch) as 'Value Inc Tax',
t2.PeriodPosted as PeriodNo,
t2.DatePosted,
t2.UserPosted
FROM (FLEET_JOB_JobDetails AS t1
LEFT JOIN FLEET_JOB_JobMaster AS t2 ON T1.JobCode = T2.JobCode)

虽然我根本不明白你为什么要这样做 - 但是你不能简单地添加t1.linetotal和t1.linegst而不将其作为SUM吗?

答案 1 :(得分:0)

删除“SUM”并添加t1.linetotal + tl.linegst解决了它。

t1.LineCost + t1.lineGST为'Value Inc Tax',