select distinct (extract(year from saledate) || extract(month from saledate)) as ym from trnsact order by ym;

select distinct (extract(year from saledate) || extract(month from saledate)) as ym from trnsact order by ym;

正在做一个练习题 'How many distinct dates are there in the saledate column of the transaction table for each month/year combination in the database?' 我找到了一个有效的查询,它显然结合了 YEAR 和 MONTH

SELECT DISTINCT (extract(year from saledate) || extract(month from saledate)) as SaleDate
FROM trnsact
ORDER BY SaleDate; 

但是||不是我们学到的东西,我在任何地方都找不到语法、描述或例子。有人可以解释一下吗?

||是字符串连接命令。在您给我们的这个查询中,数字被转换成字符串,然后连接起来。

恐怕这个解决方案是有效的。

另一个解决方案是:

select extract( year from saledate) as year_num, 
       extract( month from saledate) as month_num
  from trnsact
group by extract( year from saledate ), 
         extract( month from saledate);
SELECT saledate from trnsact group by YEAR(saledate), MONTH(saledate);

如果有人选修与我相同的课程,要找到他们所说的每个 month/year 组合的天数,我们应该在查询结果中看到:

SELECT EXTRACT(YEAR from saledate) as year_num, EXTRACT(MONTH from saledate) as month_num, COUNT(DISTINCT EXTRACT(DAY from saledate)) as day_ct
FROM trnsact
GROUP BY EXTRACT(YEAR from saledate), EXTRACT(MONTH from saledate)
ORDER BY year_num, month_num;

我也认为我们需要这个查询。

SELECT EXTRACT(YEAR from saledate) as year_num, EXTRACT(MONTH from saledate) as month_num, COUNT(DISTINCT EXTRACT(DAY from saledate)) as day_ct FROM trnsact GROUP BY EXTRACT(YEAR from saledate), EXTRACT(MONTH from saledate) ORDER BY year_num, month_num;

但不确定是否有效。你试过有效吗

这真的让我在杜克在线课程中感到烦恼,我想你也在其中。我在 Chris Dunley Mentor 回复的论坛中发现的 Recentyl:

你不能假设加入的年月的格式是'2005 8'。这是一个常见的错误。我更喜欢简单地排除 2005 年 7 月 31 日之后的所有数据,但您也可以使用 AND/OR 测试。如果你想使用连接的文本,你可以这样做

WHERE YEAR_MONTH<>'EXTRACT(YEAR from '2005-08-01')||EXTRACT(MONTH from '2005-08-01')

克里斯