Sql Server 2008 交叉表查询
我通常可以找出应用程序所需的任何 SQL 查询,但最近我被需要创建的交叉表查询所困扰,并且想知道您是否可以提供帮助?
我有 3 个表
Category(catID, catTitle)
Equipment(equipID, make, model, quantity, catID, siteID)
Site(siteID, title)
,我想创建一个交叉表查询来显示如下结果集。
Category Site1 Site2 Site3 Site4 Site5
PC 2 0 10 3 6
Camera 12 4 2 0 8
Printer 3 2 1 1 2
显示的数字表示使用设备表中的数量字段的每个站点中每个类别项目的总数。我以前从未做过交叉表查询,而且我正在努力使其工作。
I usually can figure out any sql queries I need for my applications, but I have recently been stumped by a Cross Tab query I need to create and was wondering if you could help?
I have 3 tables
Category(catID, catTitle)
Equipment(equipID, make, model, quantity, catID, siteID)
Site(siteID, title)
And I would like to create a Cross Tab query to display a result set like below
Category Site1 Site2 Site3 Site4 Site5
PC 2 0 10 3 6
Camera 12 4 2 0 8
Printer 3 2 1 1 2
The numbers displayed represent a total of each category item within each site using the quantity field withint the Equipment table. I have never had to do a Cross Tab query before and I am struggling to get this working.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该能够使用“枢轴”运算符来完成此操作。像这样的东西(尽管我确信我忽略了一些拼写或语法细节......):
这样做的问题是您需要知道要包含在查询中的确切站点 ID 集。如果您需要更动态的交叉表(就像在 Excel 中一样),那么您需要将查询文本生成为字符串并使用 sp_executesql 来运行它。在生成的文本中,包含尽可能多的“[1]、[2]、[3]、[4]、[5]...”和“[1] as site1,[2] as site2.. .”你需要的东西。
You should be able to do this with the 'pivot' operator. Something like this (though I am sure I muffed some spelling or syntax details...):
The problem with this is that you need to know the exact set of site ids you want to include in the query. If you need a more dynamic crosstab (like you can get in Excel), then you need to generate the query text as a string and use sp_executesql to run it. In the generated text, you include as many of the "[1], [2], [3], [4], [5]..." and "[1] as site1, [2] as site2..." things as you need.
我认为你缺少一个在你的站点和设备之间进行引用的表
类似这样的东西:
因为现在不可能将哪个站点区分为哪个设备
编辑:
由于siteID也在设备中我会建议另一个表,对你进行一点重构数据库(因为我真的不知道如何做到这一点)
如果您获得大量数据,那么每次您想要访问这些数据时获取数据并计算所有内容都会很混乱。
所以我建议这个表
所以当你修改数据(添加或删除设备)时你会去更新这个表,它会更清晰,你不必每次都计算每个设备的数量
I think your missing a table that make a reference between your site and equipment
Something like that :
Because now it's impossible to tell wich site as wich equipment
EDIT :
Since the siteID is also in equipment I would propose another table, a little refactor of you database (because I really don't know how to do this)
If you get a lot of data it would be a mess to fetch the data and calculate every thing every time you want to access those data.
So I propose this table
So when you modify you data (add or remove equipment) you would go update this table, it would be much clearer and you wont have to calculate the count of every equipment each time