sql查询选择条件

时间:2017-09-12 19:12:27

标签: sql netezza

我正在尝试从事务数据集(custid,supplierid,transactionid,date)编写一个sql查询。我想通过custID找到最大交易发生的供应商和最近交易发生的供应商?

输入

custID - supplierid - transactionid - date
1      - a          - 1111a         - 9/22/2017
1      - a          - 1111b         - 9/23/2017
1      - a          - 1111c         - 9/24/2017
1      - b          - 1111d         - 9/21/2017
1      - c          - 1111e         - 9/25/2017

所需

custID - suppliermax - supplierrcnt - datercnt
1      - a           - c            - 9/25/2017

2 个答案:

答案 0 :(得分:0)

如果您有更多具有最大事务数的供应商,则此查询将返回更多行。此外,它假设始终只有一个protected void DonutChart1_PreRender(object sender, EventArgs e) { SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString); con.Open(); SqlDataReader myReader = null; SqlCommand myCommand = new SqlCommand("select ( select sum([Budget Estimates 2017-18]) AS [FUNDWISE] from [dbo].[budgetbook-17-18] where Fund = '" + scnum.Text + "' ) , sum([Budget Estimates 2017-18]) as [costwise] from [dbo].[budgetbook-17-18] where Cost_ctr ='" + costcenter.Text + "'", con); myReader = myCommand.ExecuteReader(); while (myReader.Read()) { string totalfund; string totalcostbudget; totalfund = (myReader[0].ToString()); totalcostbudget = (myReader[1].ToString()); //Convert.ToDouble(totalcostbudget) / Convert.ToDouble(totalfund) * 360 = a; a = Convert.ToDouble(totalcostbudget); b = Convert.ToDouble(totalfund); piecostbudget = a / b * 100; } Double piefirst = pie100 - piecostbudget; Math.Round(piecostbudget); Math.Round(piefirst); RadHtmlChart1.Datasource = //your values RadHtmlchart1.Databound(); con.Close(); } 供应商。

supplierrcnt

答案 1 :(得分:0)

我从未与Neteeza合作,但我非常确定它支持这样的分析功能。

SELECT cust_id,
       MAX(
         CASE WHEN suppRN = 1 THEN supplier 
              ELSE NULL
          END
          ) AS supplierMax,
       MAX(
         CASE WHEN tran_rn = 1 THEN supplier 
              ELSE NULL
          END
          ) AS supplierrCnt,         
       MAX(
         CASE WHEN tran_rn = 1 THEN date_
              ELSE NULL
          END
          ) AS datercnt
  FROM (SELECT cust_id,
               supplier,
               date_,
               ROW_NUMBER() OVER
                 ( PARTITION BY cust_id
                       ORDER BY suppCnt DESC
                 ) AS suppRN,
               tran_rn
          FROM (SELECT cust_id,
                       supplier,
                       COUNT(*) OVER
                         ( PARTITION BY cust_id,
                                        supplier
                         ) AS suppCnt,
                       ROW_NUMBER() OVER
                         ( PARTITION BY cust_id
                               ORDER BY date_ DESC
                         ) AS tran_rn
                  FROM Customer
               ) AS TMP
       ) AS TMP2
 WHERE suppRN = 1
    OR tran_rn = 1       
 GROUP
    BY cust_id;