在 SQL 中将 2 列计为 1

Counting 2 Columns as 1 in SQL

我正在尝试 select 按 2 列分组的行数。例如,在下面的 table 中,我需要 return 3 给 Brenda,2 给 Jim。

bookingid bookingrep2 sales_assist
1 Brenda
2 Brenda
3 Jim Brenda
4 Jim

如果人员姓名在 bookingrep2 或 sales_assist 列中,则将其计算在内。我原以为这将是一个联合,但在这种情况下,计数加倍了。

为清楚起见编辑了查询...

SELECT        bookingid, sales_assist AS Regional_Rep
FROM            bookings
UNION ALL
SELECT bookingid, bookingRep2 AS Regional_Rep
FROM            bookings

你可能有这个人的(也许 Employee table)中央 table 我猜,如果是的话,那么你可以 inner join table 使用这两个字段,然后在 ID/Name.

上执行 group
declare @booking table(BookingID int not null identity, BookingRep2 varchar(100), SalesAssist varchar(100));

insert into @booking(BookingRep2, SalesAssist)
    values ('Brenda', null)
        , ('Brenda', null)
        , ('Jim', 'Brenda')
        , ('Jim', null)

declare @person table(Person varchar(100));

insert into @person(Person)
    values ('Brenda')
            , ('Jim')
            , ('John')

select  p.Person, count(1) as TotalTimes
from    @booking as b
        inner join @person as p on b.BookingRep2 = p.Person
                                        or b.SalesAssist = p.Person
group by p.Person

-- Output:
--    Person  |  TotalTimes
--    --------|------------
--    Brenda  |  3
--    Jim     |  2

选项 1:逆轴旋转

select   u.person
        ,count(*) as cnt
from     bookings as b unpivot (person for col in (bookingrep2, sales_assist)) as u
group by u.person

选项 2:交叉应用 + 值

select   ca.person
        ,count(*) as cnt
from     bookings as b cross apply (values (bookingrep2), (sales_assist)) as ca (person)
where    ca.person is not null
group by ca.person

+--------+-----+
| person | cnt |
+--------+-----+
| Brenda |   3 |
| Jim    |   2 |
+--------+-----+

Fiddle