划分联盟结果

时间:2017-05-22 09:11:34

标签: sql sql-server

是否可以将结果与两个选择语句分开并包含总计?

期望的结果 Required Results

我当前的代码

select sum(U.Orders) as sumtotal
from 
(
    select distinct count(p.PACKSLIP) as Orders
    from PICKHEAD as p
    where DATE_REQD = '2017-04-19'

    union 

    select distinct count(s.PACKSLIP) as Orders 
    from  SHIPHIST as s 
    where DATE_REQD = '2017-04-19' 
) AS U 

3 个答案:

答案 0 :(得分:2)

改为使用CROSS JOIN

select pOrders + sOrders as sumtotal,
       (pOrders * 100) / (pOrders + sOrders)
from 
(
    select count(p.PACKSLIP) as pOrders
    from PICKHEAD
    where DATE_REQD = '2017-04-19'
) as p
cross join
(
    select count(s.PACKSLIP) as sOrders
    from  SHIPHIST
    where DATE_REQD = '2017-04-19' 
) as s

答案 1 :(得分:0)

如果我理解正确,你想要它

select sum(U.OrderList) + sum(U.Shiplist) as totalSalesOrder,sum(U.OrderList)/ (sum(U.Shiplist)+sum(U.OrderList)) * 100 as TotalComlpetionPercentage
from 
(
    select distinct count(p.PACKSLIP) as OrderList, 0 as ShipList
    from PICKHEAD as p
    where DATE_REQD = '2017-04-19'

    union 

    select distinct  0 as OrderList, count(s.PACKSLIP) as Shiplist
    from  SHIPHIST as s 
    where DATE_REQD = '2017-04-19' 
) AS U 

答案 2 :(得分:0)

每个计数只有一个结果,可以使用交叉连接完成:

select P.Orders + S.Orders as [Total Sales],  S.Orders * 100.0 / (P.Orders + S.Orders)  as [Total Completion Percentage]
from (
        select count(p.PACKSLIP) as Orders
        from PICKHEAD as p
        where DATE_REQD = '2017-04-19'
    ) as P
cross join (
        select count(s.PACKSLIP) as Orders 
        from  SHIPHIST as s 
        where DATE_REQD = '2017-04-19' 
    ) as S