使用 @parameters 的 T-SQL 动态分组
我想实现
SELECT @param1, @param2, @param3, t.field1, sum(t.amount)
FROM table t
WHERE t.field 2 IS NOT NULL AND
t.field3ID = '12345'
GROUP BY @param1, @param2, @param3
什么是最好的方法?构建动态 SQL 是正确的方法吗?
I would like to achieve
SELECT @param1, @param2, @param3, t.field1, sum(t.amount)
FROM table t
WHERE t.field 2 IS NOT NULL AND
t.field3ID = '12345'
GROUP BY @param1, @param2, @param3
What is the best approach? Is building dynamic SQL is the way to go?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
动态 SQL 是实现这一点的唯一方法。但是,您有什么样的表,其中有一堆可选的分组列?
Dynamic SQL is the only way to go here. However, what kind of table do you have where you have a bunch of optional grouping columns?
我大胆假设您的参数包含您的字段名称。否则我看不出你为什么要把它们放在那里。
如果分组的项目在组内包含完全相同的值,您可以不使用 min 或 max 进行分组,如下所示:
您仍然会遇到 不能像这样选择字段。
您可以使用 case 语句,如果您想摆脱 group by 语句,这可以与上面的“最小/最大”哲学相结合:
我认为您可以在以下解决方案之间进行选择:
这完全取决于您将如何使用它。
I'm boldly assuming that your params hold your field names. Otherwise I see no reason why you would have them there.
If the grouped items contains exactly the same values within the groups, you could do without grouping by using min or max like this:
You would still have the problem that fields can't be selected like that.
You could use case statements, this works and can be combined with the "Min/Max" philosophy from above if you want to get rid of the group by statements:
I think you could choose between the following solutions:
It all depends on how you are going to use it.
首先,t.field1 也应该在您的组中,或者在 sql 中使用 min 或 max 等聚合函数进行处理。
这里有一些您可以使用的动态 sql。它将允许您使用不同数量的参数
First of all t.field1 should also be in your group by or handled in the sql with an aggrigate function like min or max
Here is a bit of dynamic sql you can use. It will allow you to use different number of parameters
为什么需要按显式传递到查询中的值进行分组?
从 select 语句中删除 @param1/2/3,删除 group by 并只进行常规选择。在您的代码中,将参数添加到预期结果中。否则你只是在创建网络流量。
Why would you need to group by values you are explicitly passing into your query?
Eliminate the @param1/2/3 from the select statement, eliminate the group by and just do a regular select. In your code, add your parameters to whatever is expecting the results. Otherwise you're just creating network traffic.