我已经成功地使用这种格式的查询来转动表格:
透视表
SELECT returnColumn, ISNULL(rule1,0), ISNULL(rule2,0)
FROM (SELECT DISTINCT returnColumn,
ruleColumn,
bool
FROM tableRules) AS st
PIVOT (AVG(bool) FOR ruleColumn IN (rule1,rule2) As pt
ORDER BY returnColumn
修改
我的数据透视表格式如下:
+--------------+---------------------+
| returnColumn | rule1 rule2 rule3 |
+--------------+---------------------+
| return1 | 0 1 0 |
| return2 | 1 0 1 |
+--------------+---------------------+
另一个表格otherRuleTable
包含returnColumn
和rule4
列。它看起来像这样:
+--------------+-------+
| returnColumn | rule4 |
+--------------+-------+
| return1 | 1 |
| return2 | 1 |
+--------------+-------+
我希望这种情况发生:
+--------------+---------------------------+
| returnColumn | rule1 rule2 rule3 rule4|
+--------------+---------------------------+
| return1 | 0 1 0 1 |
| return2 | 1 0 1 1 |
+--------------+---------------------------+
尝试
我认为这需要左连接,但我正在努力学习语法。我试过这个:
(SELECT returnColumn, ISNULL(rule1,0), ISNULL(rule2,0)
FROM (SELECT DISTINCT returnColumn,
ruleColumn,
bool
FROM tableRules) AS SourceTable
PIVOT (AVG(bool) FOR ruleColumn IN (rule1,rule2) As pt)
LEFT JOIN
(SELECT rule4 FROM otherRuleTable ort)
ON pt.returnColumn = ort.returnColumn
ORDER BY returnColumn
我该如何做到这一点?
ANSWER
答案 0 :(得分:0)
您的查询有两个独立的问题。一个是纯语法相关的,并已在您的第一个查询中显示。第二个是要使用的连接类型的问题。您没有提供足够的信息来回答第二个问题。但是,您可以在我的A Join A Day文章系列中找到有关不同联接类型以及何时使用的详细说明。
至于语法错误,让我们先看看数据透视查询。以下是一些测试数据设置:
MS SQL Server 2014架构设置:
CREATE TABLE dbo.tableRules(
returnColumn VARCHAR(10),
ruleColumn VARCHAR(10),
bool INT
);
CREATE TABLE dbo.otherRuleTable(
returnColumn VARCHAR(10),
rule4 INT
);
INSERT INTO dbo.tableRules(returnColumn, ruleColumn, bool)
VALUES
('return1','rule1',0),
('return1','rule2',1),
('return1','rule3',0),
('return2','rule1',1),
('return2','rule2',1),
('return2','rule3',0);
INSERT INTO dbo.otherRuleTable(returnColumn, rule4)
VALUES
('return1',0),
('return2',1);
SQL Fiddle目前已损坏,因此该链接可能无效。
简单的数据透视查询如下所示:
SELECT returnColumn, ISNULL(rule1,0) AS rule1, ISNULL(rule2,0) AS rule2, ISNULL(rule3,0) AS rule3
FROM
(
SELECT DISTINCT returnColumn, ruleColumn, bool
FROM dbo.tableRules
) AS SourceTable
PIVOT
(
AVG(bool)
FOR ruleColumn IN (rule1,rule2,rule3)
) As pt;
你的版本中的所有内容都是一个多余的括号。
要准备加入,您需要将此查询转换为子查询:
SELECT *
FROM
(
SELECT returnColumn, ISNULL(rule1,0) AS rule1, ISNULL(rule2,0) AS rule2, ISNULL(rule3,0) AS rule3
FROM
(
SELECT DISTINCT returnColumn, ruleColumn, bool
FROM dbo.tableRules
) AS SourceTable
PIVOT
(
AVG(bool)
FOR ruleColumn IN (rule1,rule2,rule3)
) As pt
)pt2;
有了这个,现在你可以加入它,好像它是一个表:
SELECT *
FROM
(
SELECT returnColumn, ISNULL(rule1,0) AS rule1, ISNULL(rule2,0) AS rule2, ISNULL(rule3,0) AS rule3
FROM
(
SELECT DISTINCT returnColumn, ruleColumn, bool
FROM dbo.tableRules
) AS SourceTable
PIVOT
(
AVG(bool)
FOR ruleColumn IN (rule1,rule2,rule3)
) As pt
)pt2
JOIN dbo.otherRuleTable ort
ON ort.returnColumn = pt2.returnColumn;
无论您使用何种连接类型,语法都是相同的。查看我的series,了解哪种类型适合您。