2016-09-16 135 views
1

我一直在爲一個客戶端系統服務工作了一段時間,需要一些幫助,我需要將兩個sql查詢合併爲一個。查詢的第一部分是查看主序列號並對其進行計數,之後查詢必須更新字段。如果有人可以幫助解決這個問題,我有兩個疑問。將兩個sql查詢合併爲一個

數查詢

SELECT master_seq, count(master_seq) as NofH 
FROM [ZS_CS_EVO_Integration].[dbo].[CS_Consolidation] 
where delivery_date = '2016-07-01' 
GROUP BY master_seq 
order by master_seq 

更新查詢

(" UPDATE [dbo].[CS_Consolidation]" 
+ " SET [split_dlv] = 1" 
+ " FROM [dbo].[CS_Consolidation]" 
+ " WHERE" 
+ " [master_seq] <> 0 AND CONVERT(DATE,delivery_date) = '" + yesterday + "'", IntConnect); 
+0

如何是這兩查詢連接? – gofr1

+0

@ gofr1這是我嘗試做的,但它是錯誤的UPDATE [dbo]。[CS_Consolidation] SET [split_dlv] = 1 FROM [dbo]。[CS_Consolidation] WHERE SELECT COUNT [master_seq]> 1 AND delivery_date ='2016-08 -15' –

+0

因此,您需要將所有'master_seq'與'COUNT(*)> 1'並更新您的表?和'delivery_date'應該是一樣的嗎? – gofr1

回答

1

你可以把第一部分爲CTE,然後加入和UPDATE:

DECLARE @delivery_date DATE = '2016-07-01' 

;WITH cte AS (
    SELECT master_seq 
    FROM [ZS_CS_EVO_Integration].[dbo].[CS_Consolidation] 
    where delivery_date = @delivery_date and [master_seq] <> 0 
    GROUP BY master_seq 
    HAVING count(master_seq) > 1 
) 

UPDATE c 
SET [split_dlv] = 1 
FROM [dbo].[CS_Consolidation] c 
INNER JOIN cte t 
    ON t.master_seq = c.master_seq and c.delivery_date = @delivery_date