用多列SQL分组

时间:2019-09-03 15:48:32

标签: sql sql-server

我有两个表componentDidMount() { this.slider.current.addEventListener('transitionend', function (e) { console.log('transitionend', e.propertyName); if (e.propertyName === 'transform') { if (this.el === 1) { var pop = [...this.state.slides]; pop.pop(); this.setState({ slides: [this.state.slides[5], ...pop] }); } else { var shift = [...this.state.slides]; shift.shift(); this.setState({ slides: [...shift, this.state.slides[0]] }); } console.log(this.slider.current); this.slider.current.style.transform = 'translate(0)'; setTimeout(() => { this.slider.current.style.transition = 'all 0.3s'; }) } }); } Contact,其中包含以下示例数据:

Account

Account

Account_Number | Account_Name 1 ABC 2 XYZ

Contact

我要确定包含多个关联联系人的所有ID | Account_Number | Contact_Name 1 1 Steve 2 1 Tom 3 2 Ryan

所需的输出:

Account_Names

我尝试了以下查询:

Contact_Name | Account_Name
Steve        | ABC
Tom          | ABC

此查询不返回任何内容,因为针对Select Distinct c.Contact_Name, a.account_Name from Contact c Inner join Account a on c.Account_Number = a.Account_Number group by a.Account_Name, c.Contact_Name having count(Account_Name) > 1; Contact_name进行了分组。

2 个答案:

答案 0 :(得分:3)

您应该仅按帐户进行汇总,然后断言任何匹配的帐户至少具有两个与之关联的联系人。

WITH cte AS (
    SELECT a.account_Name
    FROM Account a
    INNER JOIN Contact c ON c.Account_Number = a.Account_Number
    GROUP BY a.Account_Name
    HAVING MIN(c.Contact_Name) <> MAX(c.Contact_Name)
)

SELECT a.account_Name, c.Contact_Name
FROM Account a
INNER JOIN Contact c
    ON c.Account_Number = a.Account_Number
WHERE a.account_Name IN (SELECT account_Name FROM cte);

enter image description here

Demo

我这样写HAVING子句是因为,如果存在这样的索引,SQL Server可能会使用Contact_Name列上的索引。

答案 1 :(得分:0)

我只会使用exists

select a.account_name, c.contact_name
from account a join
     contact c
     on a.account_number = c.account_number
where exists (select 1
              from contact c2
              where c2.account_number = c.account_number and
                    c2.contact_name <> c.contact_name
             );

但是,假设联系人姓名是唯一的,则窗口功能可能会更简单:

select a.account_name, c.contact_name
from account a join
     (select c.*, count(*) over (partition by c.account_name) as num_contacts
      from contact c
     ) c
     on a.account_number = c.account_number
 where num_contacts > 1;