2009-12-05 33 views
0

我有這樣的數據:SQL分組...事情

ID Country City Type Qty SomeDate SomeDate1 SomeDate2 
1 Canada Ontario Type1 1  01/01/2009 02/02/2009 03/03/2009 
2 Canada Ontario Type2 1  01/01/2009 02/02/2009 03/03/2009 
3 Germany Berlin Type1 1  03/01/2007 02/01/2008 04/03/2006 
4 Germany Berlin Type1 3  03/01/2007 02/01/2008 04/03/2006 

我需要的輸出:

ID Country City  Qty SomeDate SomeDate1 SomeDate2 
1 Canada Ontario 2  01/01/2009 02/02/2009 03/03/2009 
3 Germany Berlin 4  03/01/2007 02/01/2008 04/03/2006 

同一城市之間的日期是相同的。

那麼,怎麼樣?

+2

嗯,這很簡單。您應該真的考慮學習SQL基礎知識。 – Faiz 2009-12-05 18:10:44

回答

1
SELECT MIN(ID), 
    Country, 
    City, 
    SUM(Qty) AS Qty, 
    MIN(SomeDate) AS SomeDate, 
    MIN(SomeDate1) AS SomeDate1, 
    MIN(SomeDate2) AS SomeDate2 
FROM sourceTable 
GROUP BY Country, City; 
0
SELECT 
    MIN(ID), 
    Country, 
    City, 
    SUM(Qty), 
    SomeDate, 
    SomeDate1, 
    SomeDate2 
FROM 
    MyTable 
GROUP BY 
    Country, 
    City, 
    SomeDate, 
    SomeDate1, 
    SomeDate2 
+0

您還需要在group by子句中選擇列表中的所有列。 – Faiz 2009-12-05 18:12:52

+0

@Faiz:這是不正確的。您不要在要彙總的GROUP BY子句中包含列。 – pmarflee 2009-12-05 18:35:42

+0

是的,我應該說選擇列表中的所有非聚合列。道歉... – Faiz 2009-12-06 06:41:44

0
SELECT MIN(ID), Country, City, SUM(Qty), MIN(SomeDate), MIN(SomeDate1), MIN(SomeDate2) 
FROM myTable 
GROUP BY Country, City 
0
SELECT MIN(ID) AS ID, Country, City, SUM(Qty) AS Qty, SomeDate, SomeDate1, SomeDate2 
FROM Table 
Group BY Country, City, SomeDate, SomeDate1, SomeDate2 
+1

ID和數量不應包含在GROUP BY子句中,因爲您正在聚合這些列。 – pmarflee 2009-12-05 18:37:38

+0

正確。那是個錯誤。 – Faiz 2009-12-06 06:42:17