简体   繁体   English

为另一列中的每个值选择不同的列,然后分组为

[英]Select Distinct Column For Each Value In Another Column Then Group By

I am pretty new to mySQL and I have had a hard time over the past 2 days trying to get this to work. 我对MySQL很陌生,过去两天我一直在努力使其工作。 I do not know if the title is correct in relation on what I am trying to fix, but if it is not, please correct me. 我不知道该标题是否与我要修复的内容有关,但如果不正确,请更正我。

Here is the deal: 这是交易:

I have 4 columns... id, number, package_id, and date. 我有4列... id,number,package_id和date。

id - Increments every time a new row is inserted ID -每递增一个新的行插入时间
number - Just a 2 digit number 数字 -仅2位数字
package_id - ID of package package_id-包的ID
date - date and time row was inserted 日期 -插入了日期和时间行

Here is what an example table looks like: ( I omitted the time from the date ) 这是一个示例表的样子:( 我从date省略了时间

id         number        package_id        date
---        ------        ----------        ----
1          12            20                08-01-2013
2          12            21                08-01-2013
3          12            20                08-01-2013
4          45            20                08-02-2013
5          45            22                08-02-2013
6          45            22                08-03-2013
7          12            20                08-03-2013
8          70            25                08-03-2013
9          70            26                08-03-2013
10         70            25                08-03-2013

Not only am I trying to select distinct for number and group by date. 我不仅在尝试为数字和按日期分组选择不同。 I am also trying to make sure it does it for each unique value in the package_id column. 我还试图确保对package_id列中的每个唯一值都执行此操作。

To better explain, this is what i want the output to be like when I SELECT *: 为了更好地解释,这就是我希望在SELECT *时的输出是什么样的:

id         number        package_id        date
---        ------        ----------        ----
1          12            20                08-01-2013
2          12            21                08-01-2013
4          45            20                08-02-2013
5          45            22                08-02-2013
6          45            22                08-03-2013
7          12            20                08-03-2013
8          70            25                08-03-2013
9          70            26                08-03-2013

As you can see only row 3 and 10 did not get selected because of the same number and package_id together within the same day. 如您所见,由于同一天的数字和package_id相同,因此只有第3行和第10行未被选中。

How can I accomplish this? 我该怎么做?

Is this what you are looking for: 这是你想要的:

SELECT MIN(id), number, package_id, date
FROM MyTable
GROUP by number, package_id, date

It certainly satisfies your expected result set. 它肯定满足您的预期结果集。

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

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