0

有点奇怪的请求,但是是否可以在不使用外连接的情况下让单独的 TSQL 查询并排显示数据?我想知道我是否完全复杂化了这个......

这是我想要做的:

我有 12 个查询可以计算记录数,我希望它们不是堆叠在一起,而是从右到左显示记录,就好像它们在表中一样。

所以从这些查询中:

SELECT COUNT(*) AS 'INTERNET JAN 12'
  FROM dbo.CONTACT AS AA
  JOIN dbo.Document AS BB
  ON AA.ACCOUNTNO = BB.ACCOUNTNO
 WHERE SOURCE IN ('INTERNET', 'EBAY', 'MSN', 'BING', 'GOOGLE', 'YAHOO')
   AND KEY1 = 'EA'
   AND MONTH(BB.Date) = 1
   AND  YEAR(BB.Date) = 2012

SELECT COUNT(*) AS 'INTERNET FEB 12'
  FROM dbo.CONTACT AS AA
  JOIN dbo.Document AS BB
  ON AA.ACCOUNTNO = BB.ACCOUNTNO
 WHERE SOURCE IN ('INTERNET', 'EBAY', 'MSN', 'BING', 'GOOGLE', 'YAHOO')
   AND KEY1 = 'EA'
   AND MONTH(BB.Date) = 2
   AND  YEAR(BB.Date) = 2012

 ...

SELECT COUNT(*) AS 'INTERNET DEC 12'
  FROM dbo.CONTACT AS AA
  JOIN dbo.Document AS BB
  ON AA.ACCOUNTNO = BB.ACCOUNTNO
 WHERE SOURCE IN ('INTERNET', 'EBAY', 'MSN', 'BING', 'GOOGLE', 'YAHOO')
   AND KEY1 = 'EA'
   AND MONTH(BB.Date) = 12
   AND  YEAR(BB.Date) = 2012 

我希望结果集如下所示:

 INTERNET JAN 12     INTERNET FEB 12     ...     INTERNET DEC 12
 12                  25                          31

而不是这样:

 INTERNET JAN 12
 12

 INTERNET FEB 12
 25

 ...

 INTERNET DEC 12
 31

如果不添加另一个字段并进行外部连接,这是否可能?最终结果是在 Excel 电子表格中将其作为最终用户自动更新的查询。

4

1 回答 1

1

使用临时表作为中间结果集来创建可以求和的数据怎么样?如果您的 TSQL 风格是最新的并且来自 Microsoft,那么 CTE 会这样做:

;
WITH temp (Jan12, Feb12, /* ... */ ) AS (
SELECT 
    -- Jan 12
    CASE MONTH(BB.Date)
        WHEN 1 THEN 1 
        ELSE 0 
    END,
    -- Feb 12
    CASE MONTH(BB.Date)
        WHEN 2 THEN 1 
        ELSE 0 
    END
  FROM dbo.CONTACT AS AA
  JOIN dbo.Document AS BB
  ON AA.ACCOUNTNO = BB.ACCOUNTNO
 WHERE SOURCE IN ('INTERNET', 'EBAY', 'MSN', 'BING', 'GOOGLE', 'YAHOO')
   AND KEY1 = 'EA'
   AND  YEAR(BB.Date) = 2012 
)
SELECT SUM(Jan12) AS [Internet Jan 12], SUM(Feb12) AS [Internet Feb 12] -- ... and so on

话虽这么说,您的案例可能更适合PIVOT- 如果没有您的数据库进行查询,我无法制作合理的样本;但应该很容易从文档中弄清楚。

于 2012-05-15T16:50:19.063 回答