我有两个名为clientorder
和orderitemstatus
的表。
OrderItem的
+-----+------------+-------------+
| clid| orderitem | orderstatus |
+-----+------------+-------------+
| 1 | books | 6 |
| 2 | books1 | 7 |
| 1 | books2 | 8 |
| 4 | books3 | 6 |
| 1 | books4 | 8 |
| 6 | books5 | 7 |
| 2 | books6 | 6 |
+-----+------------+-------------+
orderitemstatus
+----+---------------+
| id | iddescription |
+----+---------------+
| 6 | job held |
| 7 | pre-press |
| 8 | onqueue |
| 9 | sent |
+----+---------------+
现在我想计算客户端orderstatus
的客户端ID,结果应该是
预期输出
+------+---------+-----------+---------+------+
| clid | jobheld | pre-press | onqueue | sent |
+------+---------+-----------+---------+------+
| 1 | 2 | 1 | 0 | 2 |
| 2 | 2 | 1 | 0 | 2 |
| 3 | 4 | 1 | 0 | 2 |
| 6 | 1 | 1 | 0 | 2 |
+------+---------+-----------+---------+------+
我试过这个,但我只得到一份工作状态
查询
select count(cloi_current_status) as jobheld
from dbo.CLOI_ClientOrderItems
where cloi_current_status=9 and cl_id='1'
答案 0 :(得分:0)
您需要使用PIVOT
operator:
SELECT clid, [6] AS jobheld, [7] AS [pre-press], [8] AS onqueue, [9] AS [sent]
FROM clientorder
PIVOT
(
COUNT(orderitem)
FOR orderstatus IN ([6], [7], [8], [9])
) AS pvt
以下是我的数据结果:
+------+---------+-----------+---------+------+
| clid | jobheld | pre-press | onqueue | sent |
+------+---------+-----------+---------+------+
| 1 | 1 | 0 | 2 | 0 |
| 2 | 1 | 1 | 0 | 0 |
| 4 | 1 | 0 | 0 | 0 |
| 6 | 0 | 1 | 0 | 0 |
+------+---------+-----------+---------+------+
答案 1 :(得分:0)
也许这会有所帮助:
SELECT i.clid,
SUM(CASE WHEN s.iddescription = 'jobheld' THEN 1 ELSE 0 END) as jobheld,
SUM(CASE WHEN s.iddescription = 'prep-press' THEN 1 ELSE 0 END) as pre_press,
SUM(CASE WHEN s.iddescription = 'onqueue' THEN 1 ELSE 0 END) as onqueue,
SUM(CASE WHEN s.iddescription = 'sent' THEN 1 ELSE 0 END) as sent,
COUNT(*) AS total,
SUM(CASE WHEN s.iddescription IN ('jobheld', 'pre-press', 'onqueue') THEN 1 ELSE 0 END) as whatever
FROM orderitem i
JOIN orderstatus s
ON i.orderstatus = s.id
GROUP
BY i.clid