将两个sql查询合并为一个

时间:2016-09-16 07:06:29

标签: sql sql-server tsql

我一直在为客户端开发系统服务并需要一些帮助,我需要将两个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);

1 个答案:

答案 0 :(得分:1)

您可以将第一部分放入CTE,然后加入并更新:

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