0

我想在 sql 中按行计算记录数。

+----------+--------+----------+------ ---+------------+----------+----------+
| 产品 | 托特尔 | 卖家=COUNT(C2:F2) | 卖家a | 卖家 b | 卖家 c | 卖家 d |
+----------+--------+----------+------ ---+------------+----------+----------+
| 一个 | 3 | 23.4 | 34.2 | 空 | 34.2 | |
| 乙 | 2 | 23.4 | 空 | 34.2 | 空 | |
| c | 1 | 23.4 | 空 | 空 | 空 | |
| d | 4 | 23.4 | 34.2 | 34.2 | 34.2 | |
+----------+--------+----------+------ ---+------------+----------+----------+

我可以使用这个 =COUNT(C2:F2) 在 excel 中执行此操作。在sql中怎么做?

4

2 回答 2

1

您可以使用:

select sum(
    case when [seller a] is null then 0 else 1 end
    + case when [seller b] is null then 0 else 1 end
    + case when [seller c] is null then 0 else 1 end
    + case when [seller d] is null then 0 else 1 end
)
from your_table

这将给出所有行的总数,因为否则如何对其进行分组似乎并不明显。

于 2013-11-13T05:20:47.330 回答
0

这将起作用,但需要GROUP BY

Select 
Products,
sum(
      case when SellerA is null then 0 else 1 end
    + case when SellerB is null then 0 else 1 end
    + case when SellerC is null then 0 else 1 end
    + case when SellerD is null then 0 else 1 end
) AS Total_Seller,
SellerA,
SellerB,
SellerC,
SellerD
from MyTable
GROUP BY
Products,
SellerA,
SellerB,
SellerC,
SellerD

或者,您也可以使用它。

Select 
Products,
ISNULL((SellerA/SellerA),0)
+ISNULL((SellerB/SellerB),0)
+ISNULL((SellerC/SellerC),0)
+ISNULL((SellerD/SellerD),0) AS Total_Seller,
SellerA,
SellerB,
SellerC,
SellerD
from MyTable

SQL Fiddle 演示

于 2013-11-13T05:40:04.390 回答