需要查询信息

时间:2012-12-04 11:31:41

标签: sql

我有几张桌子

表事件

 incident_id | Customer_name
 01          | AAA
 02          | BBB
 03          | CCC
 04          | DDD

表客户

 Customer_name | Area_Name | Segment_Name 
 AAA           | JAKARTA   | PETROLEUM
 BBB           | MEDAN     | TRADITIONAL
 CCC           | JAKARTA   | TRADITIONAL
 DDD           | MEDAN     | AIRPORT

表区

 Area_Name | Phone
 JAKARTA   | 021
 MEDAN     | 022

预期的结果:

 Area    | Segment     | Number (count from Incident tabel)
 JAKARTA | PETROLEUM   | 1
 MEDAN   | TRADITIONAL | 1
 JAKARTA | TRADITIONAL | 1
 MEDAN   | PETROLEUM   | 0

任何帮助都会有所帮助

1 个答案:

答案 0 :(得分:0)

看来你总是希望区域和片段对吗?

SELECT  c.new_name, d.new_SegmentName, ISNULL(COUNT(a.CustomerId),0) as jumlah
    FROM filterednew_area c  LEFT JOIN filteredaccount b ON b.new_AreaId = c.new_areaId
    LEFT JOIN filterednew_partnersegment d ON b.new_PartnerSegmentId = d.new_partnersegmentId
    LEFT JOIN filteredIncident a ON a.CustomerId = b.AccountId
    WHERE   MONTH(a.new_trxdate) = '10' AND YEAR(a.new_trxdate) = '2012'
    AND c.new_areaid IN ('3C26906E-5C13-E211-8D39-005056850007','4E26906E-5C13-E211-8D39-005056850007')
    GROUP BY    c.new_name, d.new_SegmentName

如果你总是想要这个区域,你应该从它开始加入。
试试这个查询。

编辑:编辑后的表格解决方案

select C.Area_Name, C.Segment_Name, ISNULL(count(I.incident_id), 0)
from customer C left outer join incident I
on C.Customer_name = I.Customer_Name
group by C.Area_Name, C.Segment_Name

编辑2:使用笛卡儿积的解决方案

为了做到这一点,我想有一个表 Segment ,带有可能的段(我认为这种表存在于第一个查询中)

SELECT A.Area_Name, A.Segment_name, Count(Incident.Incident_Id) AS TOT
FROM
(
(SELECT Distinct Customer.Area_Name, Segment.Segment_name
FROM Segment, Customer 
) AS A
LEFT OUTER JOIN Customer AS C
 ON (C.Area_Name = A.Area_Name) AND (C.Segment_name = A.Segment_name)
)
LEFT OUTER JOIN Incident ON C.Customer_Name = Incident.Customer_name
GROUP BY A.Area_Name, A.Segment_name;

查询结果为

Area_Name  |    Segment_name |  TOT  

JAKARTA    |    AIRPORT     |  0  
JAKARTA    |    PETROLEUM   |   1  
JAKARTA    |    TRADITIONAL |   1  
MEDAN       |    AIRPORT     |  1  
MEDAN       |    PETROLEUM   |  0  
MEDAN       |    TRADITIONAL |  1