简体   繁体   English

选择有计数和无计数的语句

[英]Select statement with count and without

I have a SQL statement to select data: 我有一条SQL语句来选择数据:

SELECT DISTINCT count(table.data) as cntd, table.datatwo
FROM table LEFT JOIN tabletwo ON table.id=tabletwo.tableid
WHERE tabletwo.dated='2016-11-17' AND table.datafive='1'

If I keep it the way above - it returns the data as below: 如果我保持上述方式-它会返回如下数据:

cntd datatwo
4    92

However the correct data should be: 但是,正确的数据应为:

cntd datatwo
2   92
2   93

As there are two different datatwo . 由于有两个不同的datatwo两个。 When I select the statement without cont - it shows both datatwo . 当我选择不带条件的语句时,它同时显示两个datatwo

datatwo
92
93

Where am I making a mistake? 我在哪里出错?

Despite how random and unintuitive your table naming is, it appears what you want is to use a GROUP BY statement: 尽管您的表命名是多么随机和不直观,但您似乎想要使用GROUP BY语句:

SELECT
    DISTINCT count(table.data) as cntd,
    table.datatwo
FROM table
LEFT JOIN tabletwo ON table.id=tabletwo.tableid
WHERE tabletwo.dated='2016-11-17'
  AND table.datafive='1'
GROUP BY tabletwo.tableid

The COUNT statement is an aggregate function so it causes the rows to collapse down to one. COUNT语句是一个聚合函数,因此它导致行折叠为1。 Grouping by the unique value for each row will cause it to aggregate in groups. 按每一行的唯一值分组将导致其汇总成组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM