2015-04-29 75 views
1

我有2個表,預訂和文章:獨特之和不重複值

預訂

------------------------------ 
Id  | Name |  City | 
------------------------------ 
1  | Mike | Stockholm 
2  | Daniel | Gothenburg 
2  | Daniel | Gothenburg 
3  | Andre | Gothenburg (Majorna) 

文章

------------------------------------------------------------- 
ArticleId | Name  | Amount | ReservationId | 
------------------------------------------------------------- 
10   | Coconuts | 1  | 1   
10   | Coconuts | 4  | 2  
11   | Apples  | 2  | 2 
12   | Oranges  | 2  | 3 

我想選擇文章名稱和文章總數。文章數量.ArticleId和Reservations.City。

我的代碼:

SELECT distinct r.ID,a.Name as ArticleName, 
     sum(a.Amount) as ArticlesAmount, 
     substr(r.City,1,3) as ToCityName 
FROM Reservations r 
INNER JOIN Articles a 
     on r.Id = a.ReservationId 
WHERE a.Name <> '' 
GROUP BY ToCityName,a.ArticleId,a.Name 
ORDER BY ToCityName ASC 

這給了我以下結果:

Id | ArticleName | ArticlesAmount | ToCityName 

2 | Coconuts | 8   | Got 
2 | Apples  | 4   | Got 
3 | Oranges | 2   | Got 
1 | Coconuts | 1   | Sto 

但我想:

Id | ArticleName | ArticlesAmount | ToCityName 

2 | Coconuts | 4   | Got 
2 | Apples  | 2   | Got 
3 | Oranges | 2   | Got 
1 | Coconuts | 1   | Sto 

幫助,將不勝感激,並解釋請:)

Fiddle

回答

2

看看SQLFiddle

代碼:

SELECT distinct r.ID,a.Name as ArticleName, 
     sum(distinct a.Amount) as ArticlesAmount, 
     substr(r.City,1,3) as ToCityName 
FROM Reservations r 
INNER JOIN Articles a 
     on r.Id = a.ReservationId 
WHERE a.Name <> '' 
GROUP BY ToCityName,a.ArticleId,a.Name 
ORDER BY ToCityName ASC 

你想確保按照每個組出現的次數總和金額。

1

我又增加了文章又再次選擇請求的行...這裏是查詢

SELECT DISTINCT 
    r.ID, 
    a.`Name` AS ArticleName, 
    Articles.Amount, 
    substr(r.City, 1, 3) AS ToCityName 
FROM 
    Reservations r 
INNER JOIN Articles a ON r.Id = a.ReservationId 
INNER JOIN Articles ON a.ReservationId = Articles.ReservationId 
AND a.ArticleId = Articles.ArticleId 
WHERE 
    a. NAME <> '' 
GROUP BY 
    ToCityName, 
    a.ArticleId, 
    a. NAME 
ORDER BY 
    ToCityName ASC