有点奇怪的请求,但是有可能让单独的TSQL查询并排显示数据而不使用外连接吗?我想知道我是否完全复杂化了......
以下是我要做的事情:
我有12个查询会给我一个记录计数,我想要它们,而不是堆叠在一起,从右到左显示记录,好像它们在桌子上一样。 / p>
所以从这些查询:
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电子表格中将其作为最终用户自动更新的查询。
答案 0 :(得分:1)
如何使用临时表作为中间结果集来创建可以使用SUM的数据?如果您的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
- 如果没有您的数据库进行查询,我无法制作合理的样本;但要弄明白from the documentation.