查询以水平排列行

时间:2013-05-02 10:55:44

标签: sql sql-server join pivot

我有2个表需要连接并生成第三个表,其中列水平排列。表格如下: enter image description here

我需要table1table2的输出2。

我做了一些研究,发现我需要使用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脚本来创建表。

我已将脚本上传到here

1 个答案:

答案 0 :(得分:2)

问题是您正在尝试同时count并显示ProductDescription。如果您想显示ProductDescription,那么您可以通过几种不同的方式来实现此目的。

您可以count ProductDescription列,而不是将count应用于PID

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;

请参阅SQL Fiddle with Demo

或者您可以在子查询中创建第二列以返回ProductDescription两次。计数中将使用一列,第二列将用于最终显示:

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;

请参阅SQL Fiddle with Demo