SQL COUNT with conditions



我有一张表,上面列出了每种产品在市场上上市的月份。例如产品1从3月到12月可用,产品2从1月到2月可用

end_month

我使用dbFiddle来测试这个解决方案。这取决于每个月至少有一种产品可供销售。不过,也许在没有商品出售的情况下,一个月不退货更好?

可以使用@derviş-kayımbaşıoğlu方法生成月份,但不是product_id上的group,而是month。

with months as (
Select distinct start_month [month]
from Product
)
Select m.month
,count(*) [products]
from months m
left join Product p
on m.month >= p.start_month and m.month <= p.end_month
group by m.month

这样的东西需要帮助,但你可能有语法错误,因为我们不知道确切的DBMS和版本

select product_id, count(*) cnts
from table1 
inner join (
select 1 month union
select 2 union
select 3 union
select 4 union
select 5 union
select 6 union
select 7 union
select 8 union
select 9 union
select 10 union
select 11 union
select 12 union
) t2
on t2.month between table1.start_month and table1.end_month
group by product_id

最新更新