VB .NET使用SQL填充DataGridView

时间:2014-03-20 09:31:54

标签: sql sql-server vb.net

我想知道是否有人愿意帮助我,因为我正在努力解决如何解决我遇到的问题。

下面我将举例说明我想要实现的目标。

这是我的SQL数据库中的表的一个粗略示例:

+----+----------+----------+-----------+
| ID | Product  |  State   | TotalTime |
+----+----------+----------+-----------+
|  1 | Product1 | Waiting  |        10 |
|  2 | Product1 | Building |        15 |
|  3 | Product1 | Engineer |         5 |
|  4 | Product1 | Break    |        21 |
|  5 | Product1 | Waiting  |         9 |
|  6 | Product2 | Building |        11 |
|  7 | Product2 | Waiting  |        10 |
|  8 | Product2 | Break    |         5 |
|  9 | Product2 | Building |        15 |
+----+----------+----------+-----------+

现在我想要实现的是使用DataGridView将所有状态分组到产品中。

以下示例是我希望DataGridView显示数据的方式:

+----------+---------+----------+-------+----------+
| Product  | Waiting | Building | Break | Engineer |
+----------+---------+----------+-------+----------+
| Product1 |      19 |       15 |    21 |        5 |
| Product2 |      10 |       26 |     5 |        0 |
+----------+---------+----------+-------+----------+

所以基本上每个产品只有一行,然后使用SUM添加State列。

我在使用DataGridView输入内容的代码方面没有任何问题,我很乐意使用SQL将内容添加到DGV中,但是我很难看到如何将这些产品组合在一起并像上表一样显示它。

我尝试过使用DISTINCT和SUM来尝试实现这一点,但没有运气。

如果有人能指出我正确的方向,我会非常感激。

谢谢你们。

1 个答案:

答案 0 :(得分:3)

尝试此查询

SELECT * FROM
(
    SELECT PRODUCT,
           CASE WHEN State = 'Waiting' Then Sum(TotalTime) OVER (PARTITION BY State,Product ORDER BY (select Null)) Else 0 END Waiting,
           CASE WHEN State = 'Building' Then Sum(TotalTime) OVER (PARTITION BY State,Product ORDER BY (select Null)) Else 0 END Building,
           CASE WHEN State = 'Break' Then Sum(TotalTime) OVER (PARTITION BY State,Product ORDER BY (select Null)) Else 0 END Break,
           CASE WHEN State = 'Engineer' Then Sum(TotalTime) OVER (PARTITION BY State,Product ORDER BY (select Null)) Else 0 END Engineer
    From MyTable
) AS T 
    Group By Product,Engineer,Break,Waiting,Building

将其设置为DataGrid的DataSource。