TSQL:简单的枢轴,独特的细胞。不能让它工作

时间:2010-11-29 03:57:21

标签: sql sql-server tsql

问题:

我有一个包含两列的表:书籍和主题,一个主题可以有多个书籍引用它,反之亦然。

我正在尝试计算出现的不同书籍数量,并将它们应用到支点。到目前为止,我的代码结构如下:

With dataSource 
as (
select book_id, topic_id
FROM BKINFO.BookTopics
    )
select 
[CS] as 'CmpSci'
,[PGM] + [NET] + [VB] as 'CmpPgm'
,[DB] as 'DB'
,[SQL]+[MYSQL]+[ORA]+[SSRV] as 'SQL'
, [XML]as 'XML'
, [SCI] as 'Science'
, [POE] + [FCT] as 'Lit'
from dataSource
pivot(
 count(book_id)
for topic_id 
in([CS],[PGM],[NET],[VB],[DB],[SQL],[MYSQL],[ORA],[SSRV], [XML],
[SCI],  [POE], [FCT])
)tblPivot

可以使用数据透视表和其他选项来满足问题的要求。 (这是针对在线课程)数据输出应如下所示:

CmpSci      CmpPgm      DB          SQL         XML         Science     Lit
----------- ----------- ----------- ----------- ----------- ----------- -----------
0           28          9           40          2           10          3

我在这里缺少什么?我花了大约4个小时试图解决这个问题,看起来太简单了。

谢谢!

1 个答案:

答案 0 :(得分:0)

好的,所以如果本书的主题顺序无关紧要,那么解决方案实际上非常简单,只需要MINMAX定义Datasource表时的topic_id。所以,它会是这样的:

With dataSource 
as (
select book_id, MIN(topic_id) AS topic_id -- it can be MAX(topic_id) as well
FROM BKINFO.BookTopics
GROUP BY book_id
    )
select 
[CS] as 'CmpSci'
,[PGM] + [NET] + [VB] as 'CmpPgm'
,[DB] as 'DB'
,[SQL]+[MYSQL]+[ORA]+[SSRV] as 'SQL'
, [XML]as 'XML'
, [SCI] as 'Science'
, [POE] + [FCT] as 'Lit'
from dataSource
pivot(
 count(book_id)
for topic_id 
in([CS],[PGM],[NET],[VB],[DB],[SQL],[MYSQL],[ORA],[SSRV], [XML],
[SCI],  [POE], [FCT])
)tblPivot

您应该知道,该图书仅在其出现的最小(或最大)主题中计算。现在,如果您希望按照特定顺序对主题进行计算,那么我建议您创建一个表topic,并按照您喜欢的顺序添加id int列(在本例中) CS将是id 1,PGM id 2等,并且在datasource表中计算该列上的MIN