查询列之间的差异

发布于 2025-02-12 17:48:33 字数 1508 浏览 1 评论 0原文

我有此样品数据:

ID颜色气味
1红色
1黄色花状
1绿色中性
2蓝色
2蓝色花状
2蓝色花,类似于

单个ID的utiple行。

我想要的结果是要有这样的东西:

ID备注
1种不同的颜色,不同的气味
2不同的气味

相同的行值是ID,如果该列有任何差异(例如,使用ID 2,ID 2,气味像花一样,臭)说“不同的气味”

我还不是专业人士,所以我不知道是否可能。我正在考虑选择不同的ID,何时和加入的情况,但是在进行查询时,我会陷入下一步。

可以做到吗?

I have this sample data:

IDColorScent
1RedStinky
1YellowFlower-like
1GreenNeutral
2BlueStinky
2BlueFlower-like
2BlueFlower-like

There are mutiple rows pertaining to the single ID.

The result I want is to have something like this:

IDRemarks
1Different colors, different scents
2Different scents

The same value for the rows is the ID, and if there are any difference in that column (for example, with ID 2, the scents are flower-like and stinky) make a remark "Different scents"

I'm not yet a pro, so I don't know if it's possible. I'm thinking of selecting distinct IDs, case when, and joins, but when doing the query, I'm stuck on what should be the next step.

Can this be done?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

顾北清歌寒 2025-02-19 17:48:33

似乎您可以使用concat_ws的组合(假设您使用了SQL Server的完全支持版本,否则您不陈述),case计数(不同)

SELECT ID,
       CONCAT_WS(', ', CASE WHEN COUNT(DISTINCT Colour) > 1 THEN 'Different Colours' END,
                       CASE WHEN COUNT(DISTINCT Scent) > 1 THEN 'Different Scents' END) AS Remarks
FROM(VALUES(1,'Red','Stinky'),
           (1,'Yellow','Flower-like'),
           (1,'Green','Neutral'),
           (2,'Blue','Stinky'),
           (2,'Blue','Flower-like'),
           (2,'Blue','Flower-like'))V(ID, Colour, Scent)
GROUP BY ID;

Seems you can use a combination of CONCAT_WS (assuming you're on a fully supported version of SQL Server, as you don't state otherwise), CASE and COUNT(DISTINCT):

SELECT ID,
       CONCAT_WS(', ', CASE WHEN COUNT(DISTINCT Colour) > 1 THEN 'Different Colours' END,
                       CASE WHEN COUNT(DISTINCT Scent) > 1 THEN 'Different Scents' END) AS Remarks
FROM(VALUES(1,'Red','Stinky'),
           (1,'Yellow','Flower-like'),
           (1,'Green','Neutral'),
           (2,'Blue','Stinky'),
           (2,'Blue','Flower-like'),
           (2,'Blue','Flower-like'))V(ID, Colour, Scent)
GROUP BY ID;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文