0

I have a table #rah that contains only two columns (customer id and product)

Table values

product       customer id
PD        100045592
PD        100030983
PD        210330909
PDRU          200067524
PDRM          210007421

Does anyone know the best way I can use the PIVOT function in SQL Server 2008 to write this?

Desired output:

Product  Count
PD        3
PDRU      1
PDRM      1

Any help is appreciated.

4

1 回答 1

3

您不需要为此使用 PIVOT 功能。您可以通过使用聚合函数和 GROUP BY 轻松获得此结果:

select product, count(customer_id) Total
from yourtable
group by product;

请参阅SQL Fiddle with Demo。这给出了一个结果:

| PRODUCT | TOTAL |
-------------------
|      PD |     3 |
|    PDRM |     1 |
|    PDRU |     1 |

如果您希望将product名称作为列,那么您可以使用 PIVOT:

select PD, PDRU, PDRM
from yourtable
pivot
(
  count(customer_id)
  for product in(PD, PDRU, PDRM)
) piv;

请参阅SQL Fiddle with Demo。枢轴给出了一个结果:

| PD | PDRU | PDRM |
--------------------
|  3 |    1 |    1 |
于 2013-06-10T15:17:07.107 回答