将行值转换为列值——SQL PIVOT
SQL 从表中返回以下结果: CowTracking
ID cow_id barn_id
-- ------ -------
19 5 3
20 5 2
21 5 9
22 5 1
我正在尝试使用 SQL 中的 PIVOT 获取以下结果
cow_id barn1 barn2 barn3 barn4
------ ----- ----- ----- -----
5 3 2 9 1
这是我到目前为止的代码。
SELECT *
FROM
(
SELECT TOP 4 *
FROM CowTracking
WHERE cow_id = 5
) AS DataTable
PIVOT
(
MIN(barn_id) **IDK what function to use and which column to use it on**
FOR ID ??<---**NOT SURE**
IN
(
[barn1], [barn2], [barn3], [barn4]
)
) AS PivotTable
ERRORS: Error converting data type nvarchar to int
The incorrect value "barn1" is supplied in the PIVOT operator
注意:barn_id 是 varchar。无法更改数据类型。
我不是想加/乘/聚合或其他什么。我只是想将行移动到列中,
我该怎么做? 这是正确的思维过程吗?
我还需要使用 PIVOT 吗?
SQL Returns the following results from table: CowTracking
ID cow_id barn_id
-- ------ -------
19 5 3
20 5 2
21 5 9
22 5 1
I am trying to get the following results with a PIVOT in SQL
cow_id barn1 barn2 barn3 barn4
------ ----- ----- ----- -----
5 3 2 9 1
This is the code I have so far.
SELECT *
FROM
(
SELECT TOP 4 *
FROM CowTracking
WHERE cow_id = 5
) AS DataTable
PIVOT
(
MIN(barn_id) **IDK what function to use and which column to use it on**
FOR ID ??<---**NOT SURE**
IN
(
[barn1], [barn2], [barn3], [barn4]
)
) AS PivotTable
ERRORS: Error converting data type nvarchar to int
The incorrect value "barn1" is supplied in the PIVOT operator
NOTE: The barn_id is a varchar. It will not be possible to change the datatype.
I am not trying to add/multiply/aggregate or whatever. I am simply trying to move the row to a column
How would I go about doing this?
Is this the correct thought process?
Do I even need to use PIVOT?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于表中没有
barn1..4
,因此您必须以某种方式将ID
替换为相应的barn
。使用
PIVOT
的一种解决方案可能与此类似,另一种使用
CASE
和GROUP BY
的解决方案可能是这样,但本质上,这一切都归结为硬编码 < code>ID 到
谷仓
。编辑
使其更加稳健
ROW_NUMBER
来SQL语句
测试脚本
As there is no
barn1..4
in your tables, you somehow have to replace theID
's with their correspondingbarn
s.One solution using
PIVOT
might be like thisanother solution using
CASE
andGROUP BY
could bebut in essence, this all boils down to hardcoding an
ID
to abarn
.Edit
If you always return a fixed number of records, and using SQL Server you might make this a bit more robust by
ROW_NUMBER
to each resultSQL Statement
Test script