2017-08-01 34 views
0

我需要包含特定代碼的所有記錄的計數。所以,計算code == 1,code == 2, code == 3。我是新來的SQL,我不知道最有效的方法插入到這個代碼的技術。感覺最直觀的方式是說list_of_codes = [0001, 0002, 00003, 00004]並創建一個遍歷數組的循環,但我不認爲sql以這種方式工作。任何人都可以幫我弄清楚如何寫這個?如何在sql中創建循環,這是這裏最好的技術嗎?

select 
    (SELECT count(columns) as occurences 
    FROM database.table 
    where code = 00001 /*** where I need to insert a variable name */ 
    and admitdate between '01JAN2016' and '02FEB2016') 
+ (SELECT count(columns2) as occurences 
    FROM database2.table2 
    where code2 = 00001 /** where I need to insert a variable name */ 
    and startdate between '01JAN2016' and '02FEB2016') sumcount; 

最後我想輸出的樣子:

code1: 596 
code2: 39439 
code3: 30303 
+2

MySQL和tsql是互斥的。 –

+0

是否意味着每個代碼的記錄必須滿足特定條件,例如'01JAN2016'和'02FEB2016'之間的允許時間或'01JAN2016'和'02FEB2016'之間的開始時間? –

+0

@RadimBača是記錄必須滿足特定條件 –

回答

2

使用IN操作

select 
    (SELECT count(columns) as occurences 
    FROM database.table 
    where code in (1,2,3) 
    and admitdate between '20160101' and '20160202') 
+ (SELECT count(columns2) as occurences 
    FROM database2.table2 
    where code in (1,2,3) 
    and startdate between '20160101' and '20160202') sumcount; 

如果你在每個code然後

SELECT a.code, 
     a.occurences + b.occurences 
FROM (SELECT code, 
       Count(columns) AS occurences 
     FROM database.table 
     WHERE code IN (1, 2, 3) 
       AND admitdate BETWEEN '20160101' AND '20160202' 
     GROUP BY code)a 
     INNER JOIN (SELECT code, 
          Count(columns2) AS occurences 
        FROM database2.table2 
        WHERE code IN (1, 2, 3) 
          AND startdate BETWEEN '20160101' AND '20160202' 
        GROUP BY code)b 
       ON a.code = b.code 
尋找 count
+0

這工作謝謝!代碼是如何工作的?代碼的一部分工作?這是做什麼的? –

0
DECLARE 
l_output NUMBER; 

BEGIN 

FOR i IN 1..3 LOOP 
SELECT count(columns) as occurences into 1_output 
FROM database.table 
where code in (1,2,3) 
and admitdate between '20160101' and '20160202' 

DBMS_OUTPUT.PUT_LINE('Result: ' || l_output); 

END LOOP; 

END;