2012-12-12 28 views
1

我需要從許多表中生成一些大數據,關於過濾器,在那裏我還需要獲取某些列的總和以及像例子那樣的行數如何選擇總和,並使用多個連接從不同表格中計數

我有5條記錄

ID | NAME |刪除

1 | A | 1
2 | A | 0
3 | A | 1
4 | B | 1
5 | C | 1

我有查詢,

SELECT p.name, sum(p.deleted) as del, count(p.id) as numbers from products as p 
join other AS b ON p.id=b.id 

輸出我需要的是,

The sum of deleted records 

名稱|刪除|計數

A | 2 | 3
B | 1 | 1
C | 1 | 1

+1

看一看Group By子句.. – Zohaib

回答

2

試試這個::

SELECT 
p.name, 
sum(p.deleted) as del, 
count(id) as numbers 
from products as p 
join other AS b ON p.id=b.id 
group by p.name 
1

你不應該需要加入,讓您的結果。這應該工作:

SELECT name, sum(deleted), count(1) 
FROM products 
GROUP BY name 
1
SELECT name, 
     SUM(CASE WHEN deleted = 1 THEN 1 ELSE 0 END) Deletion, 
     COUNT(*) `COunt` 
FROM products 
GROUP BY name 

OR

SELECT name, 
     SUM(deleted) Deletion, 
     COUNT(*) `COunt` 
FROM products 
GROUP BY name; 
+0

我可以使用多列分組?其實什麼分組呢?你可以定義一些更多的理解 –

+1

沒有'GROUP BY',它會給你在結果列表中的單個記錄。 –

相關問題