SELECT DISTINCT用于多个字段

时间:2010-06-23 16:36:18

标签: sql

在我的表格中,我有Collection_DateTag_Date个字段,均为date类型。

我需要查询此表,将每个日期分为其组件月,日和年,但仍保持Collection_Date日期和Tag_Date日期之间的区别,而我不是想要重复。

我试过了:

SELECT DISTINCT
    MONTH(Collection_Date) AS col_month,
    DAY(Collection_Date) AS col_day,
    YEAR(Collection_Date) AS col_year,
    MONTH(Tag_Date) AS tag_month,
    DAY(Tag_Date) AS tag_day,
    YEAR(Tag_Date) AS tag_year
FROM the_table

但是,这只返回带有唯一Collection_Date Tag_Date的行。

我认为我想要的是将其分为两个查询,一个SELECT DISTINCT Collection_Date,一个Tag_Date。但是,如果可能的话,我真的想避免多次查询。

我该如何做到这一点?

2 个答案:

答案 0 :(得分:2)

此查询将返回所有唯一的collection_date和tag_date。如果collection_date与tag_date相同,则返回它们。该查询还返回它的日期类型:

SELECT DISTINCT MONTH(Collection_Date) AS m,
    DAY(Collection_Date) AS d,
    YEAR(Collection_Date) AS y
    'collection_date' AS dateType
  FROM the_table
 UNION ALL
 SELECT DISTINCT MONTH(Tag_Date) AS m,
    DAY(Tag_Date) AS d,
    YEAR(Tag_Date) AS y,
    'tag_date' AS dateType
   FROM the_table

如果只有一个tag_date或collection_date,当它们有一个共同的日期时,那么你可以使用

SELECT m, d, y, MIN(dateType) FROM (
    SELECT MONTH(Collection_Date) AS m,
        DAY(Collection_Date) AS d,
        YEAR(Collection_Date) AS y
        'collection_date' AS dateType
      FROM the_table
     UNION ALL
       SELECT MONTH(Tag_Date) AS m,
        DAY(Tag_Date) AS d,
        YEAR(Tag_Date) AS y,
        'tag_date' AS dateType
       FROM the_table      
) data
GROUP BY m, d, y

答案 1 :(得分:1)

我很确定你必须把它分开。以下将返回一个合并的结果集,但当然基本上是两个单独的查询连接在一起。

SELECT MONTH(Collection_Date) AS m,
    DAY(Collection_Date) AS d,
    YEAR(Collection_Date) AS y
 UNION --For the DISTINCT
 SELECT   MONTH(Tag_Date) AS m,
    DAY(Tag_Date) AS d,
    YEAR(Tag_Date) AS y

或者现在增加一些差异化。它将返回不同的日期和类型字段,指示日期是指标签,集合还是两者。

WITH the_table AS
(
SELECT 
    CAST('2010-06-23 00:00:00.000' AS DATETIME) AS Collection_Date, 
    CAST('2010-06-22 00:00:00.000' AS DATETIME) AS Tag_Date
UNION ALL    
SELECT 
    CAST('2010-06-25 00:00:00.000' AS DATETIME) AS Collection_Date, 
    CAST('2010-06-23 00:00:00.000' AS DATETIME) AS Tag_Date
    )
    SELECT 
    MONTH(COALESCE(T1.Collection_Date, T2.Tag_Date)) AS m,
    DAY(COALESCE(T1.Collection_Date, T2.Tag_Date)) AS d,
    YEAR(COALESCE(T1.Collection_Date, T2.Tag_Date)) AS y,
    CASE WHEN T1.Collection_Date IS NOT NULL AND T2.Collection_Date IS NOT NULL THEN 'Both'  
         WHEN T1.Collection_Date IS NOT NULL THEN 'Collection' 
         ELSE 'Tag' END 
                 AS 'Type'
FROM the_table t1
FULL OUTER JOIN the_table t2
ON T1.Collection_Date = T2.Tag_Date

返回

m           d           y           Type
----------- ----------- ----------- ----------
6           22          2010        Tag
6           23          2010        Both
6           25          2010        Collection