两年之间的SQL Query查看不同的标题

时间:2017-03-15 19:26:23

标签: sql-server distinct

我需要查询表格 2014年年份LOCAL_TITLE,SECONDARY_TITLE和FORMAT_TITLE的不同标题数量,但2013年没有?

表名:stage_data_all 列:LOCAL_TITLE,SECONDARY_TITLE,FORMAT_TITLE和YR_DATA(两个值,2013年或2014年)

我想将LOCAL_TITLE,SECONDARY_TITLE,FORMAT_TITLE与年份进行比较,只查找2014年但未在2013年的值。

谢谢。

解决方案1:

    SELECT DISTINCT COUNT(*)
    FROM (SELECT LOCAL_TITLE, SECONDARY_TITLE, FORMAT_TITLE
          FROM [STG].[dbo].[stage_data_all]
          WHERE YR_DATE = 2014) AS Y
          LEFT OUTER JOIN
          (SELECT LOCAL_TITLE, SECONDARY_TITLE, FORMAT_TITLE
          FROM [STG].[dbo].[stage_data_all]
          WHERE YR_DATE = 2013) AS X
          ON Y.LOCAL_TITLE = X.LOCAL_TITLE
          AND Y.SECONDARY_TITLE = X.SECONDARY_TITLE
          AND Y.FORMAT_TITLE = X.FORMAT_TITLE
    WHERE X.LOCAL_TITLE IS NULL
    X.SECONDARY_TITLE IS NULL
    X.FORMAT_TITLE IS NULL

感谢大家的帮助。

2 个答案:

答案 0 :(得分:1)

select distinct LOCAL_TITLE, SECONDARY_TITLE, FORMAT_TITLE from stage_data_all columns where YR_DATA != '2013' and YR_DATA = '2014'

我觉得我可能会遗漏一些东西,因为这似乎相对简单?

如果您需要这些记录的计数,只需将其包装在带有计数的选择中:

select count(*) from (select distinct LOCAL_TITLE, SECONDARY_TITLE, FORMAT_TITLE from stage_data_all columns where YR_DATA != '2013' and YR_DATA = '2014')

答案 1 :(得分:0)

由于看起来您没有任何ID,请尝试以下操作:

select distinct
  LOCAL_TITLE
, SECONDARY_TITLE
, FORMAT_TITLE
from MyTable mt
left outer join (select distinct
                  LOCAL_TITLE
                , SECONDARY_TITLE
                , FORMAT_TITLE
                from MyTable
                where YR_DATA = '2013'
                )t
                    on t.LOCAL_TITLE = mt.LOCAL_TITLE
                    and t.SECONDARY_TITLE = mt.SECONDARY_TITLE
                    and t.FORMAT_TITLE = mt.FORMAT_TITLE
where (t.LOCAL_TITLE is NULL
and t.SECONDARY_TITLE is NULL
and t.FORMAT_TITLE is NULL)
and mt.YR_DATA = '2014'
;