2017-04-08 133 views
0

我有一個表(t),我需要從中獲取一些信息。 我正在使用這2個查詢來獲取它。
但是有沒有辦法讓它在單個查詢?SQL Server加入兩個查詢

SELECT nrplu, SUM(preco) as TP, SUM(kg) as TK, seccao 
FROM t 
GROUP BY nrplu, seccao 


SELECT nrplu, count(*) as TT FROM t GROUP BY nrplu 

回答

1

這應該適合你。

WITH CTE_preselect AS 
(SELECT nrplu, count(*) as TT 
FROM t 
GROUP BY nrplu) 

SELECT t.nrplu,TT, SUM(preco) as TP, SUM(kg) as TK, seccao 
FROM t 
    JOIN CTE_preselect ON t.nrplu = CTE_preselect.nrplu 
GROUP BY t.nrplu,TT, seccao 
+0

我收到錯誤「'CTE_preselect'不是公認的GROUP BY選項。」 –

+0

改變'在t JOIN t'到'在t JOIN CTE_preselect' – TriV

+0

我更新了我的答案。 – Jason