我到处搜索,似乎无法找到解决方案。
现在我知道 UNION 的功能,但我不确定它是否正确使用。这是我的疑问:
SELECT pos.pdPosition AS [Region 1]
FROM PositionData pos
WHERE pos.PositionId = 1765
UNION ALL
SELECT pos.pdPosition AS [Region 2]
FROM PositionData pos
WHERE pos.PositionId = 1767
我想要的是用于创建新列,区域1包含数字1的数据,区域2包含数字2的数据。
我得到的是:
如何拆分/我可以使用哪种陈述?
注意:这必须是一个选择语句。
答案 0 :(得分:8)
Select
(SELECT pos.pdPosition
FROM PositionData pos
WHERE pos.PositionId = 1765) AS [Region 1]
,(SELECT pos.pdPosition
FROM PositionData pos
WHERE pos.PositionId = 1767) AS [Region 2]
答案 1 :(得分:6)
试试这个 -
<强> DDL: 强>
DECLARE @PositionData TABLE (PositionId INT, pdPosition INT)
INSERT INTO @PositionData (PositionId, pdPosition)
VALUES (1765, 1765),(1767, 1767), (1768, 1768)
我的查询:
SELECT
[Region 1] = MIN(CASE WHEN PositionId = 1765 THEN pdPosition END)
, [Region 2] = MIN(CASE WHEN PositionId = 1767 THEN pdPosition END)
FROM @PositionData
WHERE PositionId IN (1767, 1765)
bummi查询:
SELECT
(SELECT pdPosition
FROM @PositionData
WHERE PositionId = 1765) AS [Region 1]
,(SELECT pdPosition
FROM @PositionData
WHERE PositionId = 1767) AS [Region 2]
<强> 输出: 强>
Region 1 Region 2
----------- -----------
1765 1767
(1 row(s) affected)
Region 1 Region 2
----------- -----------
1765 1767
(1 row(s) affected)
查询费用: