将两个查询合并为一个。两个人都在同一个字段上分组

时间:2016-03-09 18:38:37

标签: sql

我有以下表格

table A
{SID, IP)

table B
(SID, PID)

table C
(SID, PID)

我有以下两个查询。

select IP, count (IP) as hits from A group by IP  

IP      hits
1       100
2       400
3       250

select IP, count(IP) as clicks from table A join table b on A.SID = B.SID 

IP      clicks
1       10
2       40
3       25


select IP, count(IP) as bought from A join B on A.SID = B.SID join C on C.SID = B.SID

IP      bought
1       1
2       4
3       2

如何编写一个查询,一次性生成以下结果。

IP      hits    clicks  Bought
1       100     10      1
2       400     40      4
3       250     25      2

3 个答案:

答案 0 :(得分:1)

只需加入所有人:

internal static class Program
{
    /// <summary>
    /// This is the entry point of the service host process.
    /// </summary>
    private static void Main()
    {
        try
        {
            using (var container = new UnityContainer())
            {
                container.RegisterType<IMessageProcessorClientFactory, DummyFactory>(new HierarchicalLifetimeManager());
                container.RegisterType<IMessageClusterConfigurationStore, test>(new HierarchicalLifetimeManager());

                container.WithFabricContainer();
                container.WithActor<MessageClusterActor>();
                container.WithActor<QueueListenerActor>();
                container.WithStatelessFactory<ManagementApiServiceFactory>("ManagementApiServiceType");
                container.WithActor<VmssManagerActor>();

                ServiceFabricEventSource.Current.ServiceTypeRegistered(Process.GetCurrentProcess().Id, typeof(ManagementApiService).Name);

                Thread.Sleep(Timeout.Infinite);  // Prevents this host process from terminating to keep the service host process running.
            }
        }
        catch (Exception e)
        {
            ServiceFabricEventSource.Current.ActorHostInitializationFailed(e.ToString());
            throw;
        }
    }
}

请注意,如果您的某些表格中没有某些IP值,则可能需要使用LEFT连接。

这是基本的SQL - 查看任何介绍性文字以获取更多信息。

答案 1 :(得分:0)

尝试左连接:

select a.*, b.* from (
select IP, count (IP) as hits from A group by IP)a left join (
select IP, count(IP) as clicks from table A join table b on A.SID = B.SID)b on a.ip = b.ip

..等等。

答案 2 :(得分:0)

我怀疑这可能是等效的,尽管连接可能产生很多行。这是在黑暗中刺伤,因为我不知道这些表中SID的关系。

select
    A.IP,
    count(distinct A.SID) as hits,
    count(distinct B.SID) as clicks,
    count(distinct C.SID) as bought
from
    A
    inner join B
        on A.SID = B.SID
    inner join C
        on C.SID = B.SID
group by
    A.IP