0

我有 2 个表,我需要加入并生成第三个表,其中列水平排列。表格如下: 在此处输入图像描述

table1我需要来自and的输出 2 table2

我做了一些研究,发现我需要使用PIVOT. 我也写了一些查询。我的查询是

SELECT  * FROM (
  SELECT 
  CONVERT(CHAR(4), table_2.Date, 100) + CONVERT(CHAR(4), table_2.Date, 120) as    RegistrationDate,  
  table_1.PDESC as ProductDescription from table_2 
  left outer join table_1 on table_1.PID = table_2.PID
) 
tableT
PIVOT (count(ProductDescription) FOR RegistrationDate
IN ([Jan 2009],[Feb 2009],[Mar 2009],[Apr 2009],[May 2009],[Jun 2009])) AS pvt

但是这个查询不起作用!我还附加了 SQL 脚本来创建表。

我已将脚本上传到此处

4

1 回答 1

2

The problem is that you are attempting to both count and display the ProductDescription. If you want to display the ProductDescription then there are a few different ways that you can do this.

Instead of applying the count to the ProductDescription, you can count the PID column:

SELECT  * 
FROM 
(
  SELECT CONVERT(CHAR(4), t2.Date, 100) + CONVERT(CHAR(4), t2.Date, 120) as RegistrationDate,  
    t1.ProductDesc as ProductDescription,
    t1.PID
  from table_2 t2
  left outer join table_1 t1
    on t1.PID = t2.PID
) tableT
PIVOT 
(
  count(PID) FOR RegistrationDate
  IN ([Jan 2009],[Feb 2009],[Mar 2009],[Apr 2009],[May 2009],[Jun 2009])
) AS pvt;

See SQL Fiddle with Demo.

Or you can create a second column in the subquery to return the ProductDescription twice. One column will be used in the count and the second will be used in the final display:

SELECT  * 
FROM 
(
  SELECT CONVERT(CHAR(4), t2.Date, 100) + CONVERT(CHAR(4), t2.Date, 120) as RegistrationDate,  
    t1.ProductDesc as ProductDescription,
    t1.ProductDesc as Product
  from table_2 t2
  left outer join table_1 t1
    on t1.PID = t2.PID
) tableT
PIVOT 
(
  count(ProductDescription) FOR RegistrationDate
  IN ([Jan 2009],[Feb 2009],[Mar 2009],[Apr 2009],[May 2009],[Jun 2009])
) AS pvt;

See SQL Fiddle with Demo

于 2013-05-02T11:51:37.510 回答