0

i would create a particular sql string.

I have this tables :

cities
-----------
city varchar not null  primary key
etc


weeks
-----------
week varchar not null  primary key


Insert_data
-----------
id int not null  primary key
cityID varchar
week varchar
value1 int
etc

I would to bind asp.net gridview with this table structure:

+-----+-------+-------+-------+
| city| week1 | week2 | week3 |
+-----+-------+-------+-------+
|   1 | (y/n) | (y/n) | (y/n) |
|   2 | (y/n) | (y/n) | (y/n) |
|   3 | (y/n) | (y/n) | (y/n) |
|   4 | (y/n) | (y/n) | (y/n) |
|   5 | (y/n) | (y/n) | (y/n) |
+----+-------+-------+-------+

if there are records related to that week in insert_data the value will be Y.

It's possible to create a query string for this?

4

1 回答 1

0
与往常一样,当您需要使用“按参数分组”(城市)从行创建列时,可以使用 PIVOT 运算符。http://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx

以上仅适用于 MS-SQL,不适用于 MySQL。

或者你可以用老式的方式来做

SELECT 
     cities.city
     ,SUM(CASE WHEN weeks.week = 1 THEN Insert_data.value1 ELSE 0 END) AS week1
     ,SUM(CASE WHEN weeks.week = 2 THEN Insert_data.value1 ELSE 0 END) AS week2
     ,SUM(CASE WHEN weeks.week = 3 THEN Insert_data.value1 ELSE 0 END) AS week3
     ,SUM(CASE WHEN weeks.week = 4 THEN Insert_data.value1 ELSE 0 END) AS week4
     -- ,etc. for each week (select distinct week from insert_data order by week)
FROM Insert_data
left join cities
    cities.city= Insert_data.cityID 
left join weeks
    on weeks.week = Insert_data.week

group by cities.city

无论哪种方式,您都需要动态硬编码 SQL 字符串中的星期。

您现在需要 y 和 n 的附加条件,然后您可以连接这些值。

      ,'(' + CAST(SUM(CASE WHEN weeks.week = 1 AND value1 = 1 THEN 1 ELSE 0 END) as varchar(10))
+ '/'
CAST(SUM(CASE WHEN weeks.week = 1 AND value1 = 0 THEN 1 ELSE 0 END) as varchar(10))
+ ')'
AS week1

或者如果它只是 y 或 no,那么

      ,
      CASE 
          WHEN SUM(CASE WHEN weeks.week = 1 THEN Insert_data.value1 ELSE 0 END) > 0 
               THEN 'y'
          ELSE 'n'
    END AS week1 
于 2013-11-13T08:36:07.980 回答