2017-10-20 35 views
0

的一部分,我用兩個查詢:SELECT COUNT(*)作爲更大的選擇查詢

select * from ControlPoints where LineGroup = 123001 
select count(*) from BitAssignments where LineGroup = 123001 

,以確定是否需要更新的BitAssignments表。我能否以某種方式組合這兩個查詢?

這兩個表是從外部來源填充的,主意是1)查看是否有ControlPoints的任何成員缺失,以及2)是否存在,查看是否所有BitAssignments都在表中。

架構如下:

ControlPoints table 
    LineGroup  int (primary key) 
    Name   string 
    NumControls int 
    NumInd  int 

BitAssignments table 
    LineGroup  int 
    BitPosition int 
    Mnemonic  string 

對於給定的控制點,將有隻有一個控制點表記錄,但可能有數百個在BitAssignments表位的數據行。

我需要一個查詢,告訴我外部數據中的新控制點是否已添加(或刪除),或者是否已向外部數據添加/刪除了現有控制點的新位分配。另一種方法是從頭開始重建兩個表,但此過程需要12個小時才能完成(BitAssignments中的記錄約爲300,000個)。

線沿線的東西:

select a.LineGroup b.select count(Mnemonic) from ControlPoints a, BitAssignments b where a.LineGroup=123001 

其中,當然,不能正常工作。

回答

0

你需要做2步:

  1. JOIN表

  2. 添加GROUP BY子句,因爲你正在使用COUNT彙總功能

那些2步驟後您的查詢應該是這樣的:

SELECT cp.LineGroup, cp.Name, cp.NumControls, cp.NumInd, COUNT(ba.Mnemonic) BitAssignmentsCnt 
FROM ControlPoints cp LEFT JOIN BitAssignments ba ON cp.LineGroup=ba.LineGroup 
GROUP BY cp.LineGroup, cp.Name, cp.NumControls, cp.NumInd, ba.LineGroup 

你會使用LEFT JOIN如果你想顯示所有控制點,無論他們是否有任何BitAssignments與否。如果您對BitAssignmentsCnt = 0不感興趣,則可以使用INNER JOIN而不是LEFT JOIN。

GROUP BY需要指定您在查詢中使用的所有列(在select中或在JOIN中)。

+0

絕對完美地工作;謝謝! – user3235770

0

看起來好像你想要一個簡單的羣組或一個分區的計數。

select 
    cp.* 
    ,count(b.Mnemonic) over (partition by cp.LineGroup or by NumInd) 
from 
    ControlPoints cp 
left join 
    BitAssignments b on b.LineGroup = cp.LineGroup 

或許...

select 
    cp.* 
    ,count(b.Mnemonic) 
from 
    ControlPoints cp 
left join 
    BitAssignments b on b.LineGroup = cp.LineGroup 
group by 
    cp.LineGroup 
    ,cp.Name 
    ,cp.NumControls 
    ,cp.NumInd