简体   繁体   中英

How to C# WinForm datatable loop through rows and columns to datagridview

Sql query return

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

I would like it displayed as follows on datagridview or sql query

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

In order to display what you want, you have to write query which returns your second statement. From your table it seems it is impossible.

You could consider doing a pivot on the SQL side if you are using SQL Server (>2005). The general syntax is:

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

This would create the data in the format you are looking for and would make displaying straight forward.

Here is a nice tutorial:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM