我有以下gridview:
<asp:GridView ID="gvTimeline" ShowHeader="true" runat="server" ShowHeaderWhenEmpty="true" AutoGenerateColumns="false" >
<Columns>
<asp:BoundField DataField="8" ItemStyle-Width="25%" DataFormatString="{0:dd-MM-yyyy}" />
<asp:BoundField DataField="2" ItemStyle-Width="25%" DataFormatString="{0:dd-MM-yyyy}" />
<asp:BoundField DataField="6" ItemStyle-Width="25%" DataFormatString="{0:dd-MM-yyyy}" />
<asp:BoundField DataField="4" ItemStyle-Width="25%" DataFormatString="{0:dd-MM-yyyy}" />
</Columns>
</asp:GridView>
以及以下sql表:
Id | type | date
2 | 8 | 22/09/1997
1 | 6 | 22/09/1998
3 | 4 | 22/09/1999
我想要的是运行sql行,并用与类型(仅1行)相对应的日期填充每一列。每个数据字段都是一个类型。最好的方法是什么,然后再正常访问每个id?
我希望如此:
8 2 6 4
22/09/1997 null 22/09/1998 22/09/1999
答案 0 :(得分:0)
如果仅限制这些值,那么创建一个简单的视图并绑定到 it 可能是最简单的方法。例如:
CREATE VIEW view_for_gridview_binding AS
SELECT DISTINCT
eight.[date] as '8'
, two.[date] as '2'
, six.[date] as '6'
, four.[date] as '4'
FROM table_for_gridview_question
LEFT JOIN table_for_gridview_question AS eight ON (eight.[type] = 8)
LEFT JOIN table_for_gridview_question AS two ON (two.[type] = 2)
LEFT JOIN table_for_gridview_question AS six ON (six.[type] = 6)
LEFT JOIN table_for_gridview_question AS four ON (four.[type] = 4)
GO
这里是测试:
CREATE TABLE table_for_gridview_question (
Id int NOT NULL,
[type] int NOT NULL,
[date] date NOT NULL
)
GO
INSERT INTO table_for_gridview_question
SELECT 2, 8, '1997-09-22'
UNION
SELECT 1, 6, '1998-09-22'
UNION
SELECT 3, 4, '1999-09-22'
GO
CREATE VIEW view_for_gridview_binding AS
SELECT DISTINCT
eight.[date] as '8'
, two.[date] as '2'
, six.[date] as '6'
, four.[date] as '4'
FROM table_for_gridview_question
LEFT JOIN table_for_gridview_question AS eight ON (eight.[type] = 8)
LEFT JOIN table_for_gridview_question AS two ON (two.[type] = 2)
LEFT JOIN table_for_gridview_question AS six ON (six.[type] = 6)
LEFT JOIN table_for_gridview_question AS four ON (four.[type] = 4)
GO
SELECT * FROM view_for_gridview_binding
DROP VIEW view_for_gridview_binding
DROP TABLE table_for_gridview_question
SELECT
的结果:
8 2 6 4
---------- ---------- ---------- ----------
1997-09-22 NULL 1998-09-22 1999-09-22
但是,如果您的type
可以是任何东西,则可能需要考虑阅读PIVOT
和UNPIVOT
,就像动态枢轴版本中所描述的那样答案here的一部分。