2016-10-03 79 views
1

所以我一直例如組列,如果條件得到滿足,否則,不組

|Company Name | Weight | Date |Unique ID| 
|:------------|:-------|:-----|:--------| 
|ABC   |22  |10-3 |1  | 
|ABC   |22  |10-3 |2  | 
|DEF   |50  |10-3 |3  | 
|DEF   |50  |10-3 |4  | 

下表我需要的SELECT語句顯示組僅當該組的SUM(重量)是> = 100。

所以輸出應該是:

|Company Name | Weight | Date |Unique ID| 
|:------------|:-------|:-----|:--------| 
|ABC   |22  |10-3 |1  | 
|ABC   |22  |10-3 |2  | 
|DEF   |100  |10-3 |GROUP | 

目前,我嘗試以下,但收到的無效使用集團

SELECT COMPANY_NAME, DATE, 
(CASE WHEN SUM(WEIGHT) >= 100 THEN 'GROUP' ELSE UNIQUE_ID END) AS 
    GROUP_CRITERIA 
    FROM TABLE GROUP BY COMPANY_NAME, DATE, 
    (CASE WHEN SUM(WEIGHT) >= 100 THEN 'GROUP' ELSE UNIQUE_ID END); 

回答

1

看來,你的意思是你想有和組(體重)< 100應該包含在一個組中。

要做到這一點,我做的第一GROUP BY中派生表的子查詢,那麼我可以參考的外部查詢表達式總和:

SELECT 
    CASE WHEN TOTAL_WEIGHT >= 100 THEN COMPANY_NAME ELSE 'GROUP' END AS COMPANY_NAME, 
    DATE, 
    SUM(TOTAL_WEIGHT) AS TOTAL_WEIGHT 
FROM (
    SELECT COMPANY_NAME, DATE, SUM(WEIGHT) AS TOTAL_WEIGHT 
    FROM MyTable 
    GROUP BY COMPANY_NAME, DATE 
) AS T 
GROUP BY COMPANY_NAME, DATE; 
+0

謝謝。我不得不做一些微調,但是這讓我到了我要去的地方。謝謝比爾! – user2992507

0

我想是這樣的:

SELECT DISTINCT T1.company_name, IFNULL(T2.weight, T1.weight) AS weight, IFNULL(T2.date, T1.date) AS "date", IF(T2.company_name IS NULL, T1.unique_id, T2.unique_id) 
FROM table T1 
LEFT OUTER JOIN (
    SELECT company_name, `date`, SUM(weight) AS weight 
    FROM table 
    GROUP BY company_name 
    HAVING SUM(weight) >= 100) T2 ON T2.company_name = T1.company_name 
0

這裏有一個辦法: (MAX(日期),你沒有提到如何你做團體)

SELECT COMPANY_NAME, DATE, WEIGHT, UNIQUE_ID 
FROM TABLE 
WHERE COMPANY_NAME in 
    (SELECT COMPANY_NAME FROM 
    (SELECT COMPANY_NAME, SUM(WEIGHT) FROM TABLE GROUP BY COMPANY_NAME 
     HAVING SUM(WEIGHT) < 100) u) 

UNION 

SELECT COMPANY_NAME, MAX(DATE), SUM(WEIGHT), 'GROUP' 
FROM TABLE 
WHERE COMPANY_NAME not in 
    (SELECT COMPANY_NAME FROM (SELECT COMPANY_NAME, SUM(WEIGHT) FROM TABLE GROUP BY COMPANY_NAME 
    HAVING SUM(WEIGHT) < 100) u) 

GROUP BY COMPANY_NAME 
相關問題