编辑:将两个表更新为相互同步。这些是唯一涉及的表。简而言之,我需要对所有唯一记录进行计数并以二维格式显示。
我有一张光学镜片表,示例如下:
Spherical|Cylindrical
---------------------
0 | 0.5
0.25 | 0.75
0.25 | 0.5
0 | 0
0 | 0.25
0 | 0.5
0.25 | 0.75
0.25 | 0.5
0.5 | 0
0.75 | 0
0.75 | 0
0.5 | 0.25
0.5 | 0.75
0.75 | 0.25
0.5 | 0.75
0.75 | 0.75
0.75 | 0.5
0.75 | 0.5
等等……
我想以这种方式以二维格式显示每个组合中镜头数量的鸟瞰图:
Spherical/Cylindrical|0|0.25|0.5|0.75|... upto 8 in steps of 0.25
-----------------------------------------
0 |1| 1 | 2 | 1 |
0.25 |0| 0 | 2 | 2 |
0.5 |1| 2 | 0 | 2 |
0.75 |2| 1 | 2 | 1 |
...
upto 30 in steps of 0.25
我如何在 c#.net 中使用 sql server 2008 实现它?哪种方法最好?
我有几个想法:
- 在运行时使用一些特殊查询生成一个 View 并对其进行格式化 二维
- 创建一个二维表类型(以上述格式)并更新 每次更新镜头表时进行计数。
请给我你的想法和建议。谢谢!
最佳答案
这里是一个关于如何制作 View 的示例查询:
--build table variable and sample data
DECLARE @Optical table (Spherical numeric(4,2),Cylindrical numeric(4,2))
INSERT INTO @Optical VALUES ( 0, 0.5)
INSERT INTO @Optical VALUES (0.25,0.75)
INSERT INTO @Optical VALUES (1.25, 0.5)
INSERT INTO @Optical VALUES (1.25, 0.5)
INSERT INTO @Optical VALUES ( 0, 0)
--query to use as a basis for the view
;with AllSpherical AS --this recursive CTE builds the 121 rows for: 0.00 to 30.0
(
SELECT convert(numeric(4,2),0.0) AS Spherical
UNION ALL
SELECT convert(numeric(4,2),Spherical+0.25)
FROM AllSpherical
WHERE Spherical<=29.75
)
SELECT
s.Spherical
,SUM(CASE WHEN o.Cylindrical=0.00 THEN 1 ELSE 0 END) AS c_000
,SUM(CASE WHEN o.Cylindrical=0.25 THEN 1 ELSE 0 END) AS c_025
,SUM(CASE WHEN o.Cylindrical=0.50 THEN 1 ELSE 0 END) AS c_050
,SUM(CASE WHEN o.Cylindrical=0.75 THEN 1 ELSE 0 END) AS c_075
,SUM(CASE WHEN o.Cylindrical=1.00 THEN 1 ELSE 0 END) AS c_100
,SUM(CASE WHEN o.Cylindrical=1.25 THEN 1 ELSE 0 END) AS c_125
,SUM(CASE WHEN o.Cylindrical=1.50 THEN 1 ELSE 0 END) AS c_150
,SUM(CASE WHEN o.Cylindrical=1.75 THEN 1 ELSE 0 END) AS c_175
--... add a case for all columns
FROM AllSpherical s
LEFT OUTER JOIN @Optical o ON s.Spherical=o.Spherical
GROUP BY s.Spherical
OPTION (MAXRECURSION 120)
输出:
Spherical c_000 c_025 c_050 c_075 c_100 c_125 c_150 c_175
---------- ----- ----- ----- ----- ----- ----- ----- -----
0.00 1 0 1 0 0 0 0 0
0.25 0 0 0 1 0 0 0 0
0.50 0 0 0 0 0 0 0 0
0.75 0 0 0 0 0 0 0 0
1.00 0 0 0 0 0 0 0 0
1.25 0 0 2 0 0 0 0 0
1.50 0 0 0 0 0 0 0 0
1.75 0 0 0 0 0 0 0 0
2.00 0 0 0 0 0 0 0 0
2.25 0 0 0 0 0 0 0 0
...
(121 row(s) affected)
如果您更新原始数据的次数远多于阅读此 View 的次数,则可以使用此查询构建传统 View 。这是你的选择 1
如果您计划阅读此 View 的次数远多于更新原始数据,请考虑保留该 View :Improving Performance with SQL Server 2005 Indexed Views 和 Creating Indexed Views .这基本上实现了 View ,当您插入/更新/删除基础表时, View 的存储数据会像自动系统级触发器一样更新以保持它们同步。这是您的选项 2,但系统会完成所有保持一切同步的“艰巨”工作。
关于.net - 如何为两列的值范围实现查找表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9182646/