我正在尝试将基于MySQL的应用程序迁移到Microsoft SQL Server 2005(不是选择,而是生活).
在原始应用程序中,我们几乎完全使用符合ANSI-SQL的语句,但有一个重要的例外 - 我们group_concat
经常使用MySQL的函数.
group_concat
顺便说一下,这样做:给出一张表,比如说,员工姓名和项目......
SELECT empName, projID FROM project_members;
Run Code Online (Sandbox Code Playgroud)
收益:
ANDY | A100
ANDY | B391
ANDY | X010
TOM | A100
TOM | A510
Run Code Online (Sandbox Code Playgroud)
...这是你用group_concat得到的:
SELECT
empName, group_concat(projID SEPARATOR ' / ')
FROM
project_members
GROUP BY
empName;
Run Code Online (Sandbox Code Playgroud)
收益:
ANDY | A100 / B391 / X010
TOM | A100 / A510
Run Code Online (Sandbox Code Playgroud)
所以我想知道的是:是否有可能在SQL Server中编写用户定义的函数来模拟其功能group_concat
?
我几乎没有使用UDF,存储过程或类似的东西的经验,只是直接的SQL,所以请错误地说太多的解释:)
我在postgresql上遇到了第一次痛苦的经历,当下的分钟挑战是:
如何在postgresql中执行concat_ws,通过以下方式从组中连接多个字段值:
select concat_ws(';',field_lambda) from table_lambda group by id;
Run Code Online (Sandbox Code Playgroud) 这是一个选择一组所需行的查询:
select max(a), b, c, d, e
from T
group by b, c, d, e;
Run Code Online (Sandbox Code Playgroud)
该表在列中有一个主键id
.
我想通过从每个行中获取主键来在另一个查询中标识这些行.我该怎么办?这不起作用:
select id, max(a), b, c, d, e
from T
group by b, c, d, e;
ERROR: column "T.id" must appear in the GROUP BY clause or be used in an aggregate function
Run Code Online (Sandbox Code Playgroud)
我在其他一些postgresql问题中尝试了这个,但没有运气:
select distinct on (id) id, max(a), b, c, d, e
from T
group by b, c, d, e;
ERROR: column "T.id" must appear in the GROUP BY clause …
Run Code Online (Sandbox Code Playgroud) 我希望“user_names”成为用户列表,但我无法将多个子查询项分配给“user_names”。如果子查询只返回 1 个项目,则它起作用,但如果它返回多个则不起作用。
床桌
[id]
[1]
[2]
[3]
分配表:
[id, bed_id, user_id]
[1, 1, 1]
[2, 1, 2]
用户表:
[id, 'user_name']
[1, 'John Smith']
[2, 'Jane Doe']
sql = "SELECT
b.id,
(
SELECT
u.user_name
FROM
assignments AS a
INNER JOIN
users as u
ON
a.user_id = u.id
WHERE a.bed_id = b.id
) AS user_names
FROM beds AS b"
Run Code Online (Sandbox Code Playgroud)
期望的结果是:
[1, 'John Smith, Jane Doe']
[2, '']
[3, '']
我尝试对床位 ID 进行硬编码并运行此段以获取名称列表。它没有用:
sql = """
(
SELECT
array_agg(user_name)
FROM
roomchoice_assignment AS …
Run Code Online (Sandbox Code Playgroud) 所以,我有一个非常规的问题。我希望能够将具有相同 ID 的行连接成一大行。为了说明我的问题,让我举一个例子。这是查询:
SELECT b.id AS "ID",
m.content AS "Conversation"
FROM bookings b
INNER JOIN conversations c on b.id = c.conversable_id AND c.conversable_type = 'Booking'
INNER JOIN messages m on m.conversation_id = c.id
WHERE b.state IS NOT NULL
GROUP BY 1,2
LIMIT 1000;
Run Code Online (Sandbox Code Playgroud)
这是输出:
ID **Conversation
1223 "blah, blah, blah, blah"
1223 " ... blaaaah, blah.."
1223 "more blaaah"
1223 "last blah"
5000 "new id, with more blah"
5000 "and the blah continues"
Run Code Online (Sandbox Code Playgroud)
有没有一种方法可以将对话行连接成一个聚合行,同时保留 ID?
像这样:
ID Conversation
1223 "blah, …
Run Code Online (Sandbox Code Playgroud)