MODEL DateCreated
----------------------
MODEL_1 2017-07-20
MODEL_1 2017-07-19
MODEL_1 2017-06-10
MODEL_1 2017-06-02
MODEL_2 2017-07-18
MODEL_2 2017-07-17
MODEL_2 2017-06-10
MODEL_2 2017-06-02
MODEL_3 2017-07-20
MODEL_3 2017-07-12
MODEL_3 2017-06-10
MODEL_3 2017-06-02
MODEL_3 2017-05-16
预期结果
DateCreated_Exist_In_All_Model
------------------------------
2017-06-10
2017-06-02
这意味着,只有那些存在于所有模型中的DateCreated才会显示
感谢所有愿意帮助我的人。
答案 0 :(得分:1)
一种方法是在创建日期汇总,然后将每个日期出现的不同模型的数量与表格中出现的模型总数进行比较。
SELECT
DateCreated AS DateCreated_Exist_In_All_Model
FROM [yourTable]
GROUP BY DateCreated
HAVING COUNT(DISTINCT MODEL) = (SELECT COUNT(DISTINCT MODEL) FROM yourTable)
请注意,即使您的数据集中似乎只有3个模型,我们也可以使用子查询使查询更加灵活,该子查询计算整个表中不同模型的数量。
答案 1 :(得分:0)
DECLARE @Temp table(Model varchar(1000), DateCreated date)
INSERT INTO @Temp
SELECT 'MODEL_1' , '2017-07-20'
UNION ALL
SELECT 'MODEL_1', '2017-07-19'
UNION ALL
SELECT 'MODEL_1', '2017-06-10'
UNION ALL
SELECT 'MODEL_1', '2017-06-02'
UNION ALL
SELECT 'MODEL_2', '2017-07-17'
UNION ALL
SELECT 'MODEL_2', '2017-06-10'
UNION ALL
SELECT 'MODEL_2', '2017-06-02'
UNION ALL
SELECT 'MODEL_3', '2017-07-12'
UNION ALL
SELECT 'MODEL_3 ', '2017-06-10'
UNION ALL
SELECT 'MODEL_3 ', '2017-06-02'
UNION ALL
SELECT 'MODEL_3' , '2017-05-16'
DECLARE @ModelCount int
SELECT @ModelCount = COUNT(distinct Model) from @Temp
SELECT DISTINCT DateCreated FROM (
SELECT
COUNT(MODEL) OVER(PARTITION BY DateCreated) AS Counts, Model,
DateCreated
FROM @Temp) AS D
WHERE D.Counts = @ModelCount
Or
SELECT DateCreated FROM (
SELECT
ROW_NUMBER() OVER(PARTITION BY DateCreated ORDER BY DateCreated) as Rownum,
COUNT(MODEL) OVER(PARTITION BY DateCreated) AS Counts, Model,
DateCreated
FROM @Temp) AS D
WHERE D.Counts = @ModelCount and D.Rownum = 1