試試這個SQL查詢:
SELECT SUM(CASE WHEN State = 'S' THEN 1 ELSE 0 END) AS Sold
, SUM(CASE WHEN State = 'B' THEN 1 ELSE 0 END) AS Booked
, SUM(CASE WHEN State = 'A' THEN 1 ELSE 0 END) AS Available
FROM
(SELECT S1, S2, S3, S4, S5, S6
FROM Seats) s
UNPIVOT
(State FOR Seat IN (S1, S2, S3, S4, S5, S6)) AS rows;
這裏SQL Fiddle。
在例子中,我只用6列,但在你的情況,你需要爲所有32列集,但只有一次
C#代碼:
using SqlConnection conn = new SqlConnection(yourConnectionString)
{
StringBuilder query = new StringBuilder();
query.AppendLine("SELECT SUM(CASE WHEN State = 'S' THEN 1 ELSE 0 END) AS Sold");
query.AppendLine(", SUM(CASE WHEN State = 'B' THEN 1 ELSE 0 END) AS Booked");
query.AppendLine(", SUM(CASE WHEN State = 'A' THEN 1 ELSE 0 END) AS Available");
query.AppendLine("FROM ");
query.AppendLine("(SELECT S1, S2, S3, S4, S5, S6, S7, S8");
query.AppendLine("(,S9, S10, S11, S12, S13, S14, S15, S16");
query.AppendLine("(,S17, S18, S19, S20, S21, S22, S23, S24");
query.AppendLine("(,S25, S26, S27, S28, S29, S30, S31, S32");
query.AppendLine("FROM Seats) s");
query.AppendLine("UNPIVOT");
query.AppendLine("(State FOR Seat IN (S1, S2, S3, S4, S5, S6, S7, S8");
query.AppendLine("(,S9, S10, S11, S12, S13, S14, S15, S16");
query.AppendLine("(,S17, S18, S19, S20, S21, S22, S23, S24");
query.AppendLine("(,S25, S26, S27, S28, S29, S30, S31, S32)) AS rows;");
conn.Open();
using SqlCommand command = new SqlCommand(query.ToString(), conn)
{
DataTable data = new DataTable();
data.Load(command.ExecuteReader());
//then get your values
Int32 avialable = 0;
Int32 booked= 0;
Int32 sold = 0;
if(data.Rows.Count > 0)
{
available = (Int32)data(0)("Available");
booked = (Int32)data(0)("Booked");
sold = (Int32)data(0)("Sold");
}
}
}
您是否有任何樣品與您一起工作或嘗試過? – sealz
嘗試過's1 + s2 + s3 .... AS s'? – bansi
SqlCommand cmd = new SqlCommand(「Select count(*)FROM tblCar WHERE s1 ='S'or s2 ='S'or s3 ='S'or s4 ='S'or s5 ='S'or s6 ='S '或s7 ='S'或s8 ='S'或s9 ='S'或s10 ='S'或s11 ='S'或s12 ='S'或s13 ='S'或s14 ='S'或s15 ='S'或s16 ='S'或s17 ='S'或s18 ='S'或s19 ='S'或s20 ='S'或s21 ='S'或s22 ='S'或s23 = 'S'或s24 ='S'或s25 ='S'或s26 ='S'或s27 ='S'或s28 ='S'或s29 ='S'或s30 ='S'或s31 ='S '或s32 ='S'「,con); count + = cmd.ExecuteNonQuery(); 這是我爲「已售出」字段工作的方式,但它只顯示count = -128.i的初始化數爲0 –