这是我的选择:
select s.productid, s.fromsscc, l.receiptid
from logstock s
left join log l on l.id = s.logid
where l.receiptid=1760
具有以下结果:
|Productid |SSCC |RECEIPTID
|363 |22849 |1760
|364 |22849 |1760
|1468 |22849 |1760
|1837 |22849 |1760
|384 |22849 |1760
|390 |22849 |1760
|370 |22849 |1760
|391 |22849 |1760
|371 |21557 |1760
|391 |21556 |1760
|390 |21555 |1760
|370 |21554 |1760
|389 |21553 |1760
我需要将此选择转换为此结果:
|Palet Type1 |Palet Type2
|1 |5
逻辑是:
SSCC
(示例中为22849)有多个Productid,那么它是Type 1 SSCC
(示例中为21557,21556,21555,21554,21553)只有一个Productid,那么它是类型2 我如何计算每种类型的SSCC数量(以产品为基础)?
答案 0 :(得分:2)
这应该有效:
select
SUM(CASE WHEN l.cnt > 1 THEN 1 ELSE 0 END) AS type1,
SUM(CASE WHEN l.cnt = 1 THEN 1 ELSE 0 END) AS type2
from (
select sum(COUNT(*)) over (partition by sscc) as cnt, sscc
from logstock
group by sscc
) l
这部分查询:
select sum(COUNT(*)) over (partition by sscc) as cnt, sscc
from logstock
group by sscc
返回
cnt sscc
1 21553
1 21554
1 21555
1 21556
1 21557
8 22849
因为使用(partition by sscc)
所以我们得到重复sscc的次数。上层查询使用SUM
和CASE WHEN
来计算有多少记录重复一次或多于oce的记录。
答案 1 :(得分:1)
我不确定我是否帮助你,但这应该可以解决问题:
CREATE TABLE #temp(productid int, sscc int, receiptid int)
INSERT INTO #temp(productid, sscc, receiptid)
VALUES (364,22849,1760),(1468,22849,1760),(1837,22849,1760),(384,22849,1760),(390,22849,1760),
(370,22849,1760),(391,22849,1760),(371,21557,1760),(391,21556,1760),(390,21555,1760),
(370,21554,1760),(389,21553,1760)
-- THIS is your part
SELECT t.sscc, CASE WHEN COUNT(DISTINCT productid) = 1 THEN 2 ELSE 1 END as palet_type
FROM #temp as t
GROUP BY t.sscc
DROP TABLE #temp
我也添加了一些演示代码。
这将产生以下结果:
sscc palet_type
----------- -----------
21553 2
21554 2
21555 2
21556 2
21557 2
22849 1
答案 2 :(得分:1)
你必须分组并计算。您可以使用公用表表达式来帮助简化查询。
with types (sscc, type) as (
select s.sscc,
case when count(s.productid) > 1 then 1 else 2 end as type
from stock s
where s.receiptid = 1760
group by s.sscc
)
select
(select count(*) from types where type = 1) as type_1,
(select count(*) from types where type = 2) as type_2
答案 3 :(得分:1)
这可能有用:
DECLARE @Test TABLE (ProductID INT, SSSC INT, ReceiptID INT);
INSERT INTO @Test (ProductID, SSSC, ReceiptID)
VALUES (363, 22849, 1760)
, (364, 22849, 1760)
, (1468, 22849, 1760)
, (1837, 22849, 1760)
, (384, 22849, 1760)
, (390, 22849, 1760)
, (370, 22849, 1760)
, (391, 22849, 1760)
, (371, 21557, 1760)
, (391, 21556, 1760)
, (390, 21555, 1760)
, (370, 21554, 1760)
, (389, 21553, 1760);
SELECT ProductID
, SSSC
, ReceiptID
, CASE COUNT(ProductID) OVER (PARTITION BY SSSC, ReceiptID)
WHEN 1 THEN 2
ELSE 1
END AS Type
FROM @Test;