扁平化 SQL Server 中的记录集?
假设您获得如下所示的记录集:
| ID | Foo | Bar | Red |
|-----|------|------|------|
| 1 | 100 | NULL | NULL |
| 1 | NULL | 200 | NULL |
| 1 | NULL | NULL | 300 |
| 2 | 400 | NULL | NULL |
| ... | ... | ... | ... | -- etc.
您想要:
| ID | Foo | Bar | Red |
|-----|-----|-----|-----|
| 1 | 100 | 200 | 300 |
| 2 | 400 | ... | ... |
| ... | ... | ... | ... | -- etc.
您可以使用类似的内容:
SELECT
ID,
MAX(Foo) AS Foo,
MAX(Bar) AS Bar,
MAX(Red) AS Red
FROM foobarred
GROUP BY ID
现在,当 Foo、Bar 和 Red 都是 VARCHAR 时,您如何完成类似的任务?
| ID | Foo | Bar | Red |
|-----|----------|---------|---------|
| 1 | 'Text1' | NULL | NULL |
| 1 | NULL | 'Text2' | NULL |
| 1 | NULL | NULL | 'Text3' |
| 2 | 'Test4' | NULL | NULL |
| ... | ... | ... | ... | -- etc.
致:
| ID | Foo | Bar | Red |
|-----|----------|---------|---------|
| 1 | 'Text1' | 'Text2' | 'Text3' |
| 2 | 'Text4' | ... | ... |
| ... | ... | ... | ... | -- etc.
目前主要使用 SQL Server 2000; 但可以访问 2005 年的服务器。
Say you get a recordset like the following:
| ID | Foo | Bar | Red |
|-----|------|------|------|
| 1 | 100 | NULL | NULL |
| 1 | NULL | 200 | NULL |
| 1 | NULL | NULL | 300 |
| 2 | 400 | NULL | NULL |
| ... | ... | ... | ... | -- etc.
And you want:
| ID | Foo | Bar | Red |
|-----|-----|-----|-----|
| 1 | 100 | 200 | 300 |
| 2 | 400 | ... | ... |
| ... | ... | ... | ... | -- etc.
You could use something like:
SELECT
ID,
MAX(Foo) AS Foo,
MAX(Bar) AS Bar,
MAX(Red) AS Red
FROM foobarred
GROUP BY ID
Now, how might you accomplish similar when Foo, Bar, and Red are VARCHAR?
| ID | Foo | Bar | Red |
|-----|----------|---------|---------|
| 1 | 'Text1' | NULL | NULL |
| 1 | NULL | 'Text2' | NULL |
| 1 | NULL | NULL | 'Text3' |
| 2 | 'Test4' | NULL | NULL |
| ... | ... | ... | ... | -- etc.
To:
| ID | Foo | Bar | Red |
|-----|----------|---------|---------|
| 1 | 'Text1' | 'Text2' | 'Text3' |
| 2 | 'Text4' | ... | ... |
| ... | ... | ... | ... | -- etc.
Currently working primarily with SQL Server 2000; but have access to 2005 servers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
上面的查询适用于 VARCHAR 字段,就像适用于 INT 字段一样。 不过,查询的问题是,如果有两行具有相同的 ID,并且这两行的“Foo”列中都有某些内容,则只会显示具有最高值的行(对于 INT 和 VARCHAR) 。
The query you had above works just fine for VARCHAR fields as it did for INT fields. The problem with your query though is that if you have two rows with the same ID, and both of those rows had something in the "Foo" column, then only the one with the highest value (both for INT and VARCHAR) will be displayed.
我目前无法访问 SQL2K 框,但 select max(column) 将在 2005 年对 nvarchars 起作用。唯一的问题是,如果原始表中每个 id 的每列下都有多个文本值...
回报
I don't have access to a SQL2K box at the minute but select max(column) will work on nvarchars in 2005. The only problem will be if you have multiple text values under each column for each id in your original table...
returns