SQL查询摘要

时间:2013-11-13 08:25:50

标签: mysql sql

我会创建一个特定的sql字符串。

我有这张表:

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

我想用这个表结构绑定asp.net gridview:

+-----+-------+-------+-------+
| 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) |
+----+-------+-------+-------+

如果在insert_data中有与该周相关的记录,则该值将为Y。

可以为此创建一个查询字符串吗?

1 个答案:

答案 0 :(得分: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或不,那么

      ,
      CASE 
          WHEN SUM(CASE WHEN weeks.week = 1 THEN Insert_data.value1 ELSE 0 END) > 0 
               THEN 'y'
          ELSE 'n'
    END AS week1