复杂的跨表查询

时间:2013-08-30 11:47:28

标签: sql-server database

我需要帮助来构建查询。问题是,我没有权限对DB进行设计更改。考虑到这一点,我的表格如下:

Problems
ID
日期
LastStory
UserAssignedTo

Stories
ID
ProblemID
UserThatMadeTheStory
DateOfStory
状态

如何存储数据: 系统上的任何用户都可以创建“问题”。每次创建问题时,还会在表Stories上插入一行,链接到Problems表的“ProblemID”,状态为“2”,并且“UserThatMadeTheStory”分配给实际用户“问题” ”。 稍后,问题是“重新分配”给其他用户。此过程创建一个“Stories”条目,其中包含描述并将“UserThatMadeTheStory”更改为分配给它的用户,同时,在“Problems”表中更改“UserAssignedTo”以保存新用户已分配至。 然后,要知道世界卫生组织实际打开了问题,我必须在“故事”中查找第一条记录,其中“ProblemID”与我想知道的匹配。

现在,我遇到的问题是:

我必须在上个月查找用户创建的问题。 怎么会是查询?

编辑:

SELECT s.* 
FROM stories s
INNER JOIN (SELECT problemid, min(id) AS Id FROM stories GROUP BY problemid) s2 ON s.id = s2.id
INNER JOIN (SELECT UserThatMadeTheStory, DateOfStory, Id FROM stories) s3 ON s2.id = s3.id
WHERE s3.UserThatMadeTheStory = <the one you're interested in>
AND s3.DateOfStory = <dates you're interested in>

这确实按预期工作,现在我还没有问题......

  

如果你可以帮助我......我必须列出X用户创建的问题。 AND HAVENT在“过去2天”(或指定的任何日期[它可以是查询的外部输入]中得到任何“故事”)

2 个答案:

答案 0 :(得分:0)

SELECT s.* 
FROM stories s
INNER JOIN (SELECT problemid, min(id) FROM stories GROUP BY problemid) s2 ON s.id = s2.id
WHERE s2.UserThatMadeTheStory = <the one you're interested in>
AND s2.DateOfStory = <dates you're interested in>

编辑:

实际上,上面的SQL中有一些错误 - 抱歉。我已修改它,所以它现在应该工作。注意,我必须添加第三个连接以确保您获得首次记录该问题的用户/日期:

SELECT s.* 
FROM stories s
INNER JOIN (SELECT problemid, min(id) AS Id FROM stories GROUP BY problemid) s2 ON s.id = s2.id
INNER JOIN (SELECT UserThatMadeTheStory, DateOfStory, Id FROM stories) s3 ON s2.id = s3.id
WHERE s3.UserThatMadeTheStory = <the one you're interested in>
AND s3.DateOfStory = <dates you're interested in>

编辑2:

对于您的新问题(应该在新问题上发布):

SELECT p.* 
FROM stories s
INNER JOIN (SELECT problemid, min(id) AS Id FROM stories GROUP BY problemid) s2 ON s.id = s2.id
INNER JOIN (SELECT UserThatMadeTheStory, DateOfStory, Id FROM stories) s3 ON s2.id = s3.id
INNER JOIN problems p ON s.problemid = p.id
WHERE s3.UserThatMadeTheStory = <the one you're interested in>
AND NOT EXISTS (SELECT 1 FROM stories s4 WHERE s4.problemid = p.id AND s4.id <> s2.id AND DATEDIFF(dd,s4.DateOfStory,GETDATE()) <= 2)

答案 1 :(得分:0)

我想你会想要GROUP BY

SELECT 
    MIN(ID),
    MIN(ProblemID)
FROM
    Stories
GROUP BY
    ID,
    ProblemID

上面的示例应该为您提供每个故事的第一个带有ProblemID的ID