我有下表Tracking
:
+----------+------------+-----------+---------+
| 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 |
+------------+------+-------+
你能给我一个提示吗?
谢谢。
答案 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
答案 1 :(得分:0)
您需要做的是: 1.获取pageCount的总和以供复制 2.获取pageCount的总和以进行打印 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
答案 2 :(得分:-1)
不是三列,而是
select DeviceName, JobType, sum(PageCount) as count
from table
group by DeviceName, JobType