如何将C#WinForm数据表循环遍历行和列到datagridview

时间:2014-01-27 21:46:50

标签: c# sql datagridview

SQL查询返回

cid   Sid  SalesName  Ratio  Price   Amount

1    01   Mike        11      80      120
1    11   Salier      10      70       90
3    04   Amy          8      60      200
3    01   Mike        25      110     600

我希望它在datagridview或sql查询

上显示如下
cid   Mike_Price Mike_Amount Balance  Salier_Price  Salier_Amount Balance Amy_Price   Amy_Amount
1         80        120         40        70               90       20      0            0
3        110        600         490       0                0        0      60          200

2 个答案:

答案 0 :(得分:0)

为了显示您想要的内容,您必须编写返回第二个语句的查询。从你的桌子看,这似乎是不可能的。

答案 1 :(得分:0)

如果您使用的是SQL Server(> 2005),您可以考虑在SQL端进行转移。 一般语法是:

SELECT
    [non-pivoted column], -- optional
    [additional non-pivoted columns], -- optional
    [first pivoted column],
    [additional pivoted columns]
FROM (
    SELECT query producing sql data for pivot
        -- select pivot columns as dimensions and
        -- value columns as measures from sql tables
) AS TableAlias
PIVOT
(
    <aggregation function>(column for aggregation or measure column) -- MIN,MAX,SUM,etc
    FOR [<column name containing values for pivot table columns>]
    IN (
        [first pivoted column], ..., [last pivoted column]
      )
) AS PivotTableAlias
ORDER BY clause -- optional

这将以您正在寻找的格式创建数据,并且可以直接显示。

这是一个很好的教程:

http://www.kodyaz.com/articles/t-sql-pivot-tables-in-sql-server-tutorial-with-examples.aspx

相关问题