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

时间:2022-09-23 13:09:14

I am pretty new to mySQL and I have had a hard time over the past 2 days trying to get this to work. 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.

我是mySQL的新手,在过去的两天里我一直很努力让这个工作起来。我不知道标题是否与我想要解决的问题有关,但如果不是,请纠正我。

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
number - Just a 2 digit number
package_id - ID of package
date - date and time row was inserted

id - 每次插入新行时递增数字 - 只需2位数字package_id - 包日期ID - 插入日期和时间行

Here is what an example table looks like: (I omitted the time from the 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?

我怎么能做到这一点?

1 个解决方案

#1


1  

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.

它当然满足您的预期结果集。

#1


1  

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.

它当然满足您的预期结果集。