我有一个采用这种(非常困惑)格式的表格。这是表中间列的快照,这就是数据中存在大洞的原因(其他列中包含这些行的内容)。
+---------------+--------------------+--------------+--------------+
| upsell1 | upsell2 | upsell3 | upsell4 |
+---------------+--------------------+--------------+--------------+
| | | Car Kit | Scented Tabs |
| | | | |
| | | | |
| | Fiters | | |
| NULL | NULL | NULL | NULL |
| | | | |
| | Car Kit | Scented Tabs | |
| | | | |
| | | | |
+---------------+--------------------+--------------+--------------+
我希望获得一个输出,该输出可以对每个产品进行分组和计数,无论它出现在哪一列中。
+--------------+---------------+
| Product | Product Count |
+--------------+---------------+
| Car Kit | 2 |
| Scented Tabs | 2 |
| Fiters | 1 |
+--------------+---------------+
通常情况下,如果全部都在一列中,那么使用 group by 命令将 X 作为第 1 列并将 count(X) 作为第 2 列就很容易了,但我正在寻找一种方法来获取这些不同的信息正确地组合在一起。
注意:我无法更改表格的结构(令我非常懊恼)
最佳答案
我会使用apply
来做到这一点:
select v.upsell, count(*)
from t cross apply
(values (upsell1), (upsell2), (upsell3), (upsell4)) v(upsell)
where v.upsell is not null
group by v.upsell;
你的问题有点不清楚空白是什么。您可能想要:
where v.upsell is not null and v.upsell <> ''
甚至:
where v.upsell is not null and ltrim(rtrim(v.upsell)) <> ''
关于SQL Server 2018如何将信息分组到不同的列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52481865/