2015-11-06 40 views
0

我有以下的表稱爲TrackingSQL - 多個查詢對同桌

+----------+------------+-----------+---------+ 
| DeviceID | DeviceName | PageCount | JobType | 
+----------+------------+-----------+---------+ 
|  1 | Device1 |  22 | print | 
|  2 | Device2 |  43 | copy | 
|  1 | Device1 |  11 | copy | 
|  2 | Device2 |  15 | print | 
|  3 | Device3 |  65 | copy | 
|  4 | Device4 |   1 | copy | 
|  3 | Device3 |  17 | copy | 
|  2 | Device2 |  100 | copy | 
|  1 | Device1 |  632 | print | 
|  2 | Device2 |   2 | print | 
|  3 | Device3 |  57 | print | 
+----------+------------+-----------+---------+ 

我試圖創建副本總輸出查詢和打印每個設備,像這樣的例子:

+------------+------+-------+ 
| DeviceName | Copy | Print | 
+------------+------+-------+ 
| Device1 | 11 | 654 | 
| Device2 | 143 | 17 | 
| Device3 | 82 | 57 | 
| Device4 | 1 |  0 | 
+------------+------+-------+ 

你能給我一個提示嗎?

謝謝。

+3

一個提示爲「按組」。 – M4ks

+0

請添加您正在使用的數據庫系統 –

回答

2

我能想到的最簡單的方法是:

SELECT DeviceName, 
     SUM(CASE WHEN JobType = 'copy' THEN PageCount ELSE 0 END) AS Copy, 
     SUM(CASE WHEN JobType = 'print' THEN PageCount ELSE 0 END) AS Print 
FROM Tracking 
GROUP BY DeviceName 
+0

非常感謝您的幫助。 –

-1

那麼不分三路,但

select DeviceName, JobType, sum(PageCount) as count 
from table 
group by DeviceName, JobType 
+0

不完全是他想要的格式,但數字是正確的 –

0

你需要做的是:共PAGECOUNT爲共PAGECOUNT副本 2.獲取和 1.使用和打印 3.加入兩個結果

獲得資金很容易,只需要:

1) select DeviceName, sum(pageCount) as copy from Tracking where jobType = 'copy' group by deviceName 

2) select DeviceName, sum(pageCount) as print from Tracking where jobType = 'print' group by deviceName 

,並加入他們:

select A.deviceName, copy, print from 
(select DeviceName, sum(pageCount) as copy from Tracking 
where jobType = 'copy' group by deviceName) as A 
inner join 
(select DeviceName, sum(pageCount) as print from Tracking 
where jobType = 'print' group by deviceName) as B 
ON A.deviceName = B.deviceName 
+0

非常感謝您的幫助。 –