0

我有两个表,Main并且Details- 它们具有一对多的关系,其中一行Main可能在Details.

我正在尝试创建一个查询,该查询返回来自 的所有信息Main,以及其中的关联行是否Details包含一组代码中的一个。当然,由于它是一对多的,因此其中可能存在几个这样的代码Details- 我不想重复计算行数。我也需要重复几次。

我想要的是这样的:

SELECT m.*, CASE WHEN x.ID IS NOT NULL THEN 1 ELSE 0 END AS Codes1, CASE WHEN y.ID IS NOT NULL THEN 1 ELSE 0 END AS Codes2
FROM [Main] m
LEFT JOIN EXISTS(SELECT d.ID FROM [Details] d WHERE m.ID = d.ID AND d.Code IN (<<Codes1>>)) x
LEFT JOIN EXISTS(SELECT d.ID FROM [Details] d WHERE m.ID = d.ID AND d.Code IN (<<Codes2>>)) y

有没有办法做到这一点?(这似乎应该是显而易见的,我过于复杂到第 n 级,但我真的是在画一个空白......

4

3 回答 3

2

从查询中删除EXISTS并添加DISTINCT

SELECT DISTINCT
   m.*, 
   CASE WHEN x.ID IS NOT NULL THEN 1 ELSE 0 END AS Codes1, 
   CASE WHEN y.ID IS NOT NULL THEN 1 ELSE 0 END AS Codes2 
FROM [Main] m 
LEFT JOIN (SELECT d.ID FROM [Details] d WHERE m.ID = d.ID AND d.Code IN (<<Codes1>>)) x 
LEFT JOIN (SELECT d.ID FROM [Details] d WHERE m.ID = d.ID AND d.Code IN (<<Codes2>>)) y 
于 2012-09-05T08:10:22.773 回答
0

我认为这会起作用:

SELECT  M.*, 
        CASE WHEN C1.Codes IS NULL THEN 0 ELSE 1 END as Codes1,
        CASE WHEN C2.Codes IS NULL THEN 0 ELSE 1 END as Codes2
FROM    Main M
LEFT
JOIN    
(
    SELECT  d.Id,
            COUNT(d.Code) as Codes
    FROM    Details d
    WHERE   d.Code in (<<Codes1>>)
    GROUP 
    BY      d.Id
) C1
    ON C1.Id = M.Id
LEFT
JOIN    
(
    SELECT  d.Id,
            COUNT(d.Code) as Codes
    FROM    Details d
    WHERE   d.Code in (<<Codes2>>)
    GROUP 
    BY      d.Id
) C2
    ON C2.Id = M.Id

如果您不需要 M.* 那么这可能会更好:

SELECT  M.Id, 
        SUM(CASE WHEN D1.Id IS NULL THEN 0 ELSE 1 END) AS Codes1Count,
        SUM(CASE WHEN D2.Id IS NULL THEN 0 ELSE 1 END) AS Codes2Count
FROM    Main M
LEFT
JOIN    Details D1
        ON  D1.Id = M.Id 
        AND D1.Code in (<<Codes1>>)
LEFT
JOIN    Details D2
        ON  D2.Id = M.Id 
        AND D2.Code in (<<Codes2>>)
GROUP 
BY      M.Id
于 2012-09-05T07:11:35.283 回答
0

这是一个精简版的代码,可以让你得到你想要的

SELECT abb1.*, abb2.mycount 
FROM Main AS abb1
    JOIN (SELECT Main.ID, COUNT(Details.ID) AS mycount
         FROM Main 
            JOIN Details on Details.ID = Main.ID
         GROUP BY Main.ID) AS abb2
于 2012-09-05T14:10:20.327 回答