如何在SQL中合并多个结果行

时间:2012-08-13 14:31:23

标签: sql-server-2008 codeigniter activerecord

这是我想要做的:我有以下表格:

User
id     name  
1      user1


Emails
id     email                           user_id
1      something@somewhere.com         1
2      something_else@somewhere.com    1

Addresses
id    address  user_id
 1    Here     1
 2    There    1

我想要做的是每个用户只包含一行的SELECT,无论他有多少封电子邮件和地址。问题是我还需要一个地址才能看到。所以我需要我的结果看起来像这样:

name         email                address  total_emails total_addresses
user1        something@somewhere  Here     2            2

我想到GROUP BY,但由于我使用COUNT函数来获取电子邮件和地址的数量,因此我被迫对所有列进行GROUP BY,因此每个组合得到一个结果......

我想在SQL中做什么?是否可以使用CodeIgniter ActiveRecord?

2 个答案:

答案 0 :(得分:0)

我不熟悉sql-server但在mysql中我会写这个:

SELECT t1.id AS user_id, 
       t2.email AS user_email,
       t3.address AS user_address,
       (SELECT count(*) from emails WHERE user_id = t1.id) as total_emails,
       (SELECT count(*) from emails WHERE user_id = t1.id) as total_addresses,
FROM user t1
LEFT JOIN emails t2 on t1.id = t2.user_id
LEFT JOIN addresses t3 ON t1.id = t3.user_id
GROUP BY t1.id

如果sql server支持子查询,它应该可以工作

答案 1 :(得分:0)

;With user_details AS
(
SELECT
name
,_Addresses.address
,_email.email
,row_number() OVER (PARTITION BY name ORDER BY _email.id ASC) AS email_row
,COUNT(_email.email) OVER (PARTITION BY name) AS email_count
,row_number() OVER (PARTITION BY name ORDER BY _addresses.id ASC) AS address_row
,COUNT(_addresses.address) OVER (PARTITION BY name) AS address_count
FROM _user
LEFT OUTER JOIN _email on _email.user_id = _user.id
LEFT OUTER JOIN _Addresses ON _Addresses.user_id = _user.id
)
SELECT 
name
,MAX(CASE WHEN email_row = 1 THEN email END) AS email
,MAX(CASE WHEN address_row = 1 THEN address END) AS address
,MAX(email_count) as total_emails
,MAX(address_count) as total_addresses
FROM user_details
GROUP BY name