SQL新手,想要一些帮助"旋转"一张桌子。这就是我要做的事情......
Oracle数据库格式:
╔═════════════╦══════════╦═══════════╦═══════════╗
║ Sale Start ║ Sale End ║ Store ║ Promotion ║
╠═════════════╬══════════╬═══════════╬═══════════╣
║ 1/1 ║ 4/1 ║ Nike ║ 10% OFF ║
║ 1/1 ║ 4/1 ║ Adidas ║ 20% OFF ║
║ 1/1 ║ 6/1 ║ Reebok ║ 30% OFF ║
║ 2/1 ║ 4/1 ║ Nike ║ 40% OFF ║
║ 2/1 ║ 4/1 ║ Reebok ║ 50% OFF ║
║ 3/1 ║ 4/1 ║ Adidas ║ 60% OFF ║
║ 3/1 ║ 4/1 ║ Sketchers ║ 70% OFF ║
╚═════════════╩══════════╩═══════════╩═══════════╝
期望的输出:
╔═════════════╦══════════╦═════════╦═════════╦═════════╗
║ Sale Start ║ Sale End ║ Nike ║ Adidas ║ Reebok ║
╠═════════════╬══════════╬═════════╬═════════╬═════════╣
║ 1/1 ║ 4/1 ║ 10% OFF ║ 20% OFF ║ ║
║ 1/1 ║ 6/1 ║ ║ ║ 30% OFF ║
║ 2/1 ║ 4/1 ║ 40% OFF ║ ║ 50% OFF ║
║ 3/1 ║ 4/1 ║ ║ 60% OFF ║ ║
╚═════════════╩══════════╩═════════╩═════════╩═════════╝
回答潜在问题:
Stack Overflow的新功能所以请告诉我是否可以澄清任何内容。谢谢!
答案 0 :(得分:1)
我认为您只需要一个标准的数据透视查询:
SELECT
[Sale Start],
[Sale End],
MAX(CASE WHEN Store = 'Nike' THEN Promotion END) AS Nike,
MAX(CASE WHEN Store = 'Adidas' THEN Promotion END) AS Adidas,
MAX(CASE WHEN Store = 'Reebok' THEN Promotion END) AS Reebok
FROM yourTable
WHERE Store IN ('Nike', 'Adidas', 'Reebok')
GROUP BY
[Sale Start],
[Sale End];
不包括Sketchers数据的要求是通过在select子句中没有一个术语来转动该数据来满足的。
请注意,您没有告诉我们您使用的是哪个数据库。我假设SQL Server,其中带空格的列名可以使用方括号进行转义。在其他数据库中,您需要以其他方式转义。