将多个SELECTS放入单个结果行

时间:2018-12-28 15:52:22

标签: sql-server

我正在尝试将2条select语句合并到一个查询中,如果可能的话,我希望最后得到1行,其中包含4列(每个查询2个)。我确定我过去曾经使用过类似以下内容的东西,但是却收到错误消息:“当未将EXISTS引入子查询时,在选择列表中只能指定一个表达式。”

谢谢

SELECT 
(SELECT
SUM(SO.new_profits_sales_totalactualprofit) as TAP_AFFINITY, 
SUM(SO.new_profits_sales_totaldealprofit) as TDP_AFFINITY
FROM new_dealsheet DS
LEFT JOIN salesorder SO ON DS.new_dsheetid = SO.salesorderid
LEFT JOIN New_salespeople SP ON DS.New_SalespersonId = SP.New_salespeopleId 
WHERE CAST(SO.New_purchaseordersenddate as date) = CAST(GETDATE() as date)  
AND SO.New_PassedToAdmin = 1
AND SP.New_SalesGroupIdName = 'AFFINITY') as t1,

(SELECT
SUM(SO.new_profits_sales_totalactualprofit) as TAP_GENUS, 
SUM(SO.new_profits_sales_totaldealprofit) as TDP_GENUS
FROM new_dealsheet DS
LEFT JOIN salesorder SO ON DS.new_dsheetid = SO.salesorderid
LEFT JOIN New_salespeople SP ON DS.New_SalespersonId = SP.New_salespeopleId 
WHERE CAST(SO.New_purchaseordersenddate as date) = CAST(GETDATE() as date)  
AND SO.New_PassedToAdmin = 1
AND SP.New_SalesGroupIdName = 'GENUS') as t2

1 个答案:

答案 0 :(得分:2)

您可以交叉连接两个单行结果集以将它们组合在一起。

WITH t1 AS
(
SELECT
SUM(SO.new_profits_sales_totalactualprofit) as TAP_AFFINITY, 
SUM(SO.new_profits_sales_totaldealprofit) as TDP_AFFINITY
FROM new_dealsheet DS
LEFT JOIN salesorder SO ON DS.new_dsheetid = SO.salesorderid
LEFT JOIN New_salespeople SP ON DS.New_SalespersonId = SP.New_salespeopleId 
WHERE CAST(SO.New_purchaseordersenddate as date) = CAST(GETDATE() as date)  
AND SO.New_PassedToAdmin = 1
AND SP.New_SalesGroupIdName = 'AFFINITY'
), t2 AS
(
SELECT
SUM(SO.new_profits_sales_totalactualprofit) as TAP_GENUS, 
SUM(SO.new_profits_sales_totaldealprofit) as TDP_GENUS
FROM new_dealsheet DS
LEFT JOIN salesorder SO ON DS.new_dsheetid = SO.salesorderid
LEFT JOIN New_salespeople SP ON DS.New_SalespersonId = SP.New_salespeopleId 
WHERE CAST(SO.New_purchaseordersenddate as date) = CAST(GETDATE() as date)  
AND SO.New_PassedToAdmin = 1
AND SP.New_SalesGroupIdName = 'GENUS'
)
SELECT *
FROM t1 cross join T2

但是更好的方法是在一个查询中完成所有操作

SELECT SUM(CASE WHEN SP.New_SalesGroupIdName = 'GENUS' THEN SO.new_profits_sales_totalactualprofit END) AS TAP_GENUS,
       SUM(CASE WHEN SP.New_SalesGroupIdName = 'GENUS' THEN SO.new_profits_sales_totaldealprofit END)   AS TDP_GENUS,
       SUM(CASE WHEN SP.New_SalesGroupIdName = 'AFFINITY' THEN SO.new_profits_sales_totalactualprofit END) AS TAP_AFFINITY,
       SUM(CASE WHEN SP.New_SalesGroupIdName = 'AFFINITY' THEN SO.new_profits_sales_totaldealprofit END)   AS TDP_AFFINITY
        FROM   new_dealsheet DS
               LEFT JOIN salesorder SO
                      ON DS.new_dsheetid = SO.salesorderid
               LEFT JOIN New_salespeople SP
                      ON DS.New_SalespersonId = SP.New_salespeopleId
        WHERE  CAST(SO.New_purchaseordersenddate AS DATE) = CAST(GETDATE() AS DATE)
               AND SO.New_PassedToAdmin = 1
               AND SP.New_SalesGroupIdName IN ( 'GENUS','AFFINITY')