使用计数语法正确更新

时间:2018-07-23 16:01:48

标签: sql sql-server sql-server-2008

我试图通过一个查询更新多个键记录,但是我不知道正确的语法。

这是我的尝试:

UPDATE hL
SET hL.[QUANTITY_COMPLETED] = (SELECT COUNT([SERIAL_NUMBER]) 
                               FROM [dbo].[ORDER_ITEMS] oO
                               INNER JOIN [dbo].[JOB_HISTORY] jH ON jH.[ORDER_NUMBER] = Oo.[ORDER_NUMBER]
                               INNER JOIN [dbo].[JOB_HISTORY_LINE] hL ON hL.[LINE_NUMBER] = oO.[LINE_NUMBER]
                               WHERE oO.[LINE_NUMBER] = hL.[LINE_NUMBER])
FROM [dbo].[JOB_HISTORY_LINE] hL

问题:以上内容会将SUMORDER_ITEMS项中的JOB_HISTORY_LINE粘贴在JOB_HISTORY_LINE中的所有条目中。这是不对的。

LINE_NUMBER仅包含与ORDER_NUMBER关联的每个ORDER_ITEMS的信息。 LINE_NUMBER中的每个项目都有一个关联的ORDER_NUMBERJOB_HISTORY,可以通过ORDER_NUMBER进行引用,其中包含JOB_HISTORY_LINES

目标COUNT中的每一行都应显示SERIAL_NUMBERS表中ORDER_ITEMS中与之相关的 import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.games.Games; public class BaseActivity extends AppCompatActivity { public static final String TAG = "QuizHero"; public GoogleApiClient apiClient; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Test Google Play Services apiClient = new GoogleApiClient.Builder(this) .addApi(Games.API) .addScope(Games.SCOPE_GAMES) .enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() { @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { Log.e(TAG, "Could not connect to Play games services"); } }).build(); } }

请帮助我弄清楚这一点,以便我了解为什么要搞砸了:)

2 个答案:

答案 0 :(得分:1)

也许您正在寻找的是相关子查询:

UPDATE hL
    SET hL.[QUANTITY_COMPLETED] = (SELECT COUNT([SERIAL_NUMBER])
                                   FROM [dbo].[ORDER_ITEMS] oO INNER JOIN
                                        [dbo].[JOB_HISTORY] jH
                                        ON jH.[ORDER_NUMBER] = Oo.[ORDER_NUMBER]
                                   WHERE oO.[LINE_NUMBER] = hL.[LINE_NUMBER]
                                  )
    FROM [dbo].[JOB_HISTORY_LINE] hL;

答案 1 :(得分:0)

UPDATE [hL]
SET [hL].[QUANTITY_COMPLETED]=[oo].[Total]
FROM [dbo].[JOB_HISTORY_LINE] [hL]
LEFT JOIN
 (
 SELECT [oO].[LINE_NUMBER]
       ,Count([SERIAL_NUMBER]) AS [Total]
 FROM [dbo].[ORDER_ITEMS] AS [oO]
 INNER JOIN [dbo].[JOB_HISTORY] AS [jH]
       ON [jH].[ORDER_NUMBER]=[Oo].[ORDER_NUMBER]
 INNER JOIN [dbo].[JOB_HISTORY_LINE] AS [hL]
       ON [hL].[LINE_NUMBER]=[oO].[LINE_NUMBER]
 GROUP BY [oO].[LINE_NUMBER]
 ) AS [OO]
 ON [oO].[LINE_NUMBER]=[hL].[LINE_NUMBER];