我有2个表,我正在使用join从这两个表中获取常用记录。
我使用了以下查询但我的问题是我将记录加倍。
查询如下,你能帮帮我吗?
查询#1:(正确输出)
mysql> SELECT DISTINCT
xId1 AS xId1,
xArea AS xArea,
YEAR (
STR_TO_DATE(
`xDate`,
'%d/%m/%Y'
)
) AS xYear
FROM
doTable1 AA
LEFT JOIN doTable2 BB ON AA.xId1 = BB.xId2
WHERE
xArea IN ('XX1A')
AND YEAR (
STR_TO_DATE(
`xDate`,
'%d/%m/%Y'
)
) = 2016;
+-----------+-------+-------+
| xId | xArea | xYear |
+-----------+-------+-------+
| 91623545 | XX1A | 2016 |
| 89748942 | XX1A | 2016 |
| 115956872 | XX1A | 2016 |
| 103595808 | XX1A | 2016 |
| 103623873 | XX1A | 2016 |
| 103623892 | XX1A | 2016 |
| 103623872 | XX1A | 2016 |
| 103623894 | XX1A | 2016 |
| 112072738 | XX1A | 2016 |
| 112072751 | XX1A | 2016 |
| 117818773 | XX1A | 2016 |
| 117818753 | XX1A | 2016 |
| 117885105 | XX1A | 2016 |
| 117960040 | XX1A | 2016 |
| 117885111 | XX1A | 2016 |
+-----------+-------+-------+
15 rows in set
查询#2:(输出错误,因为2016年我有18条记录 - 加倍存在 - 而不是查询#1 上的15条记录):
mysql> SELECT
DISTINCT COUNT(*) AS xQQQ,
xArea AS xArea,
YEAR (
STR_TO_DATE(
xDate,
'%d/%m/%Y'
)
) AS xYear
FROM
doTable1 AA
LEFT JOIN doTable2 BB ON AA.xId1 = BB.xId2
WHERE xArea IN ('XX1A')
GROUP BY
xArea,
xYear;
+------+-------+-------+
| xQQQ | xArea | xYear |
+------+-------+-------+
| 4 | XX1A | 2014 |
| 49 | XX1A | 2015 |
| 18 | XX1A | 2016 |
+------+-------+-------+
3 rows in set
答案 0 :(得分:1)
修改了你的SQL。如果你想要不同的计数,必须像这样使用
COUNT(DISTINCT xId1 )
请跑步看看。
SELECT
COUNT(DISTINCT xId1 ) AS xQQQ,
xArea AS xArea,
YEAR (
STR_TO_DATE(
`DATA PUBBLICAZIONE`,
'%d/%m/%Y'
)
) AS xYear
FROM
doTable1 AA
LEFT JOIN doTable2 BB ON AA.xId1 = BB.xId2
WHERE xArea IN ('XX1A')
GROUP BY
xArea,
xYear;