所以这将是我的第一次询问,呜!
我正在尝试按照相应的日期代码在列中组合相似的值。因此,对于日期5213,使用下面的示例表,我想返回给定事件的所有可能组合的总和。
示例表:
╔══════╦═════════╦═════════╦═════════╗ ║ Date ║ Event1 ║ Event2 ║ Event3 ║ ╠══════╬═════════╬═════════╬═════════╣ ║ 5213 ║ A ║ C ║ E ║ ║ 5213 ║ A ║ D ║ E ║ ║ 5212 ║ A ║ D ║ F ║ ║ 5212 ║ A ║ C ║ F ║ ║ 5212 ║ B ║ D ║ F ║ ║ 5212 ║ A ║ D ║ F ║ ║ 5212 ║ B ║ D ║ F ║ ╚══════╩═════════╩═════════╩═════════╝
我希望看到的回报:
╔══════╦══════════════╦════════════════╗ ║ Date ║ Comb_Event ║ Count_of_Event ║ ╠══════╬══════════════╬════════════════╣ ║ 5213 ║ ACE ║ 1 ║ ║ 5213 ║ ADE ║ 1 ║ ║ 5212 ║ ADF ║ 2 ║ ║ 5212 ║ ACF ║ 1 ║ ║ 5212 ║ BDF ║ 2 ║ ╚══════╩══════════════╩════════════════╝
我不确定如何连接值以及如何在单独的列中计算所述值。任何方向都将不胜感激。
谢谢!
答案 0 :(得分:0)
如何组合值取决于数据库。这是一个基本SQL问题中唯一棘手的部分。以下是使用标准concat()
函数的示例:
select date, concat(event1, event2, event3) as comb_event, count(*)
from example
group by date, concat(event1, event2, event3)
order by date, concat(event1, event2, event3);
根据数据库的不同,语法可能是:
select date, event1 || event2 || event3 as comb_event, count(*)
from example
group by date, event1 || event2 || event3
order by date, event1 || event2 || event3;
或:
select date, event1 + event2 + event3 as comb_event, count(*)
from example
group by date, event1 + event2 + event3
order by date, event1 + event2 + event3;
或事件:
select date, event1 & event2 & event3 as comb_event, count(*)
from example
group by date, event1 & event2 & event3
order by date, event1 & event2 & event3;
答案 1 :(得分:0)
这应该适用于SQL Server和MySQL:
select count(*) as count_of_events, dates
,concat(event1, event2, event3) as comb_event
from test
group by dates, concat(event1, event2, event3)
这是DEMO