How can use 'AS' syntax? - mysql

I need to different data in different table I am trying use AS
I try all code all of them work but one by one , ı am not working together
I try two ways but ıts nor working ı thought roung syntax ı resarch but ı am new in sql
My first way:
string cmd = #" SELECT COUNT(Ref) AS data,";
cmd += #" (select count(CustomerID) as data2 from Contract where DATEDIFF(DAY,StartDate,GETDATE()) between 0 and 30),";
cmd += #" (select count(distinct(CustomerID)) as data3 from Contract where FinishDate > GETDATE()),";
cmd += #" (select count(Ref) as data4 from Support where DATEDIFF(DAY,StartDate,GETDATE()) between 0 and 30)";
cmd += #" FROM Customer WHERE (Deleted = 0 or Deleted is null) ";
My second way:
string cmd = #" SELECT COUNT(Ref) ,";
cmd += #" (select count(CustomerID) from Contract where DATEDIFF(DAY,StartDate,GETDATE()) between 0 and 30) as data2 ,";
cmd += #" (select count(distinct(CustomerID)) from Contract where FinishDate > GETDATE()) as data3,";
cmd += #" (select count(Ref) from Support where DATEDIFF(DAY,StartDate,GETDATE()) between 0 and 30) as data4";
cmd += #" FROM Customer WHERE (Deleted = 0 or Deleted is null) AS data ";

The alias must be assigned at a query level, not in subquery (1st variant).
WHERE condition cannot have an alias (2nd variant).
SELECT COUNT(Ref) AS data,
( select count(CustomerID)
from Contract
where DATEDIFF(DAY,StartDate,GETDATE()) between 0 and 30) as data2 ,
( select count(distinct(CustomerID))
from Contract
where FinishDate > GETDATE()) as data3,
( select count(Ref)
from Support
where DATEDIFF(DAY,StartDate,GETDATE()) between 0 and 30) as data4
FROM Customer
WHERE (Deleted = 0 or Deleted is null)

Related

getting error from mysqli_fetch_array

My query line is:
SELECT TR.*,
PL.*, DE.*,
( DE.power + DE.stamina + DE.violence + DE.speed + DE.shooting + DE.scoring + DE.pass + DE.ball_control + DE.talent ) AS TPOWER,
strftime('%Y-%d-%m', DE.age, 'unixepoch') AS age
FROM `transfers` TR JOIN `players` PL ON TR.player_id=PL.id
JOIN `playerdetails` DE ON TR.player_id=DE.player_id
WHERE PL.position = 'MD' AND ( age >= '20' AND age <= '24' )
AND PL.firstname = 'a' AND PL.lastname = 'b' AND TPOWER >= '1'
AND TPOWER <= '5' AND TR.price >= '20' AND TR.price <= '50'
ORDER BY age DESC
What's wrong with this query?
An error occurred:
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in E:\EasyPHP-Devserver-16.1\eds-www\classes\DB.php on line 15
MySQL doesn't have a function called strftime(). You might want date_format() instead:
SELECT . . .
date_format(de.age, '%Y-%d-%m') AS age
However, that seems like a strange way to express the age (which is usually an integer, number, or interval).
Your query could have other errors as well. You should check the error messages that are returned.

How to convert sql to hql with join and max

I am trying to make this query in hql so i don't have to mapper the query result into my java object , but after trying different options, i still can't make it work. Is it possible to perform this query in hql in any way? The query is:
select t.*
from part_movement t
join
( select id_block_movement, max(start_date) as somedate
from part_movement
where id_area_final_destination = 1
and ((id_area_destination != id_area_final_destination and id_user_receiver is not null) or
(id_area_destination = id_area_final_destination and id_user_receiver is null))
group by id_block_movement
) s
on s.id_block_movement = t.id_block_movement
and s.somedate= t.start_date;
ok i got it finally!! It was: (feels wired answearing myself without having any answear from someone else )
Query q2 = s.createQuery(" from PartMovement t "
+ " WHERE t.areaByIdAreaFinalDestination = ? "
+ " AND t.startDate IN (select max(b.startDate) from PartMovement b "
+ " WHERE ((b.areaByIdAreaDestination != b.areaByIdAreaFinalDestination and b.usersByIdUserReceiver is not null) OR "
+ " (b.areaByIdAreaDestination = b.areaByIdAreaFinalDestination and b.usersByIdUserReceiver is null)) "
+ " group by b.idBlockMovement )");

LIMIT CLAUSE With union

I have this kind of query. I am using limit, but this query gives me 20 results. Can anybody tell me why
SELECT
*,
`tablename`.`bookmark_id` as `bookmark_id`,
`tablename`.`bookmark_date` as `bookmark_date`
FROM ( (" + sql1 + ")
UNION ALL (" + sql2 + ")
UNION ALL (" + sql3 + ") ) AS tablename
WHERE `bookmark_id`
NOT IN
(SELECT `table1`.`bookmark_id`
FROM (
(SELECT `user_bookmarks`.`bookmark_id`
FROM `user_bookmarks`
WHERE `user_bookmarks`.`bookmark_id` = `bookmark_id`
AND `user_id` = 26)
UNION
(SELECT `bookmark_id`
FROM `user_deleted_bookmarks`
WHERE `user_id` = ?)
) AS `table1`)
GROUP BY bookmark_id
ORDER BY `bookmark_date`
DESC limit 17, 20
Thanks
From the SELECT docs
With one argument, the value specifies the number of rows to return from the beginning of the result set:
SELECT * FROM tbl LIMIT 5; # Retrieve first 5 rows
With two arguments, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. The offset of the initial row is 0 (not 1):
SELECT * FROM tbl LIMIT 5,10; # Retrieve rows 6-15
I think you want LIMIT 16, 4
When you use limit, second argument is number of results to return.
See : http://dev.mysql.com/doc/refman/5.0/en/select.html
In your case you want :
SELECT .... LIMIT 16,4
You will get 4 rows : 17, 18, 19 and 20.
SELECT *,`tablename`.`bookmark_id` as `bookmark_id`,`tablename`.`bookmark_date` as `bookmark_date` FROM ( (" + sql1 + ") union all (" + sql2 + ") union all (" + sql3 + ") ) AS tablename WHERE `bookmark_id` NOT IN (SELECT `table1`.`bookmark_id` FROM ((SELECT `user_bookmarks`.`bookmark_id` FROM `user_bookmarks` WHERE `user_bookmarks`.`bookmark_id` = `bookmark_id` AND `user_id` = 26) UNION (SELECT `bookmark_id` FROM `user_deleted_bookmarks` WHERE `user_id` = ?)) AS `table1`) GROUP BY bookmark_id ORDER BY `bookmark_date`
DESC limit 16, 4;
for getting result 17,18,19,20
it's count start from 17th position and give next 4 values

how to use limit keyword in oracle

I am retrieving data from table but instead of all row, I want 20 rows at a time for pagination. For this I use limit keyword which work perfectly in Mysql but not in Oracle.
Code:
"select "+ "C.CONTRACTOR_ID,C.CONTRACTOR_NAME,nvl(C.CONTACT_PERSON_1,'-'),nvl(C.CONTACT_PERSON_2,'-'),C.REGISTRATION_NO,CRA.DESCRIPTION REG_AUTH_NAME,"+
"to_char(C.VALID_FROM,'dd/mm/yyyy'),to_char(C.VALID_TO,'dd/mm/yyyy'),CC.DESCRIPTION CONTRACTOR_CLASS,C.INCORP_PLACE,"+
"IT.DESCRIPTION INCORP_TYPE,nvl(to_char(C.DATE_OF_INCORP,'dd/mm/yyyy'),'-') DATE_OF_INCORP,C.ADDRESS1,nvl(C.ADDRESS2,'-'),nvl(C.EMAIL_ID,'-'),"+
"nvl(C.WEBSITE_URL,'-'),nvl(C.PHONE_NO,'-'),nvl(C.FAX_NO,'-'),nvl(C.MOBILE_NO,'-'),C.BANK_NAME,C.BANK_BRANCH,C.ACCOUNT_NO,C.IFSC_CODE," +
"C.PAN_NO,nvl(C.TIN_NO,'-'),nvl(C.CST_NO,'-') "+
"from "+
"CONTRACTOR C "+
"inner join CONTRACTOR_REG_AUTH CRA on CRA.REG_AUTH_ID=C.REG_AUTH_ID "+
"inner join CONTRACTOR_CLASS CC on CC.CLASS_ID=C.CONTRACTOR_CLASS_ID "+
"inner join INCORPORATION_TYPE IT on IT.INCORP_TYPE=C.INCORP_TYPE "+
"limit " + offset + ", " + noOfRecords ";
Here no order by keyword is there. I am retrieving data from different table and then display only 20 rows at a time.
In Oracle, you can use the special rownum variable. This example behaves like limit FirstRow, NrOfRows:
select *
from (
select *
, rownum as rn
from YourTable
order by
id
) as SubQueryAlias
where FirstRow <= rn
and rn < FirstRow + NrOfRows
An optimized version of this query from AskTom, linked from this SO question:
select *
from (
select /*+ FIRST_ROWS(n) */
rownum as rn
, *
from (
select *
from YourTable
order by
id
) as SubQueryAlias1
where rownum <= FirstRow + NrOfRows
) as SubQueryAlias2
where rn >= FirstRow

Merging records with consecutive dates

I have the following problem in a Database using Access 2007 as front end and SQL2005 as back-end.
In Table A I have the following data structure
Table A
ID Date Supplier_ID
1 10/22/2009 1
2 10/23/2009 1
3 10/24/2009 2
4 10/25/2009 2
5 10/26/2009 1
I need to merge values that have consecutive dates and the same Supplier_ID, increment a new column (Days) for each of these consecutive records and them write the data into Table B, so that I have
Table B
ID Date Supplier_ID Days
1 10/22/2009 1 2
2 10/24/2009 2 2
3 10/26/2009 1 1
Only consecutive days should be merged. Hence ID 5 in table A has is added to table B as a new record. It's been some time since I've been working with Access VBA and wondered what the right approach to this would be.
Here's some ANSI-92 Query Mode syntax SQL DDL and DML to recreate the table and a possible solution:
CREATE TABLE TableA
(
ID INTEGER NOT NULL UNIQUE,
[Date] DATETIME NOT NULL,
Supplier_ID INTEGER NOT NULL
);
INSERT INTO TableA (ID, [Date], Supplier_ID)
SELECT DT1.ID, DT1.[Date], DT1.Supplier_ID
FROM (
SELECT DISTINCT 1 AS ID, '2009-10-22 00:00:00' AS [Date], 1 AS Supplier_ID FROM Customers
UNION ALL
SELECT DISTINCT 2, '2009-10-23 00:00:00', 1 FROM Customers
UNION ALL
SELECT DISTINCT 3, '2009-10-24 00:00:00', 2 FROM Customers
UNION ALL
SELECT DISTINCT 4, '2009-10-25 00:00:00', 2 FROM Customers
UNION ALL
SELECT DISTINCT 5, '2009-10-26 00:00:00', 1 FROM Customers
) AS DT1;
CREATE VIEW TableA_StartDates (Supplier_ID, start_date)
AS
SELECT T1.Supplier_ID, T1.[Date]
FROM TableA AS T1
WHERE NOT EXISTS (
SELECT *
FROM TableA AS T2
WHERE T2.Supplier_ID = T1.Supplier_ID
AND DATEADD('D', -1, T1.[Date]) = T2.[Date]
);
CREATE VIEW TableA_EndDates (Supplier_ID, end_date)
AS
SELECT T3.Supplier_ID, T3.[Date]
FROM TableA AS T3
WHERE NOT EXISTS (
SELECT *
FROM TableA AS T4
WHERE T4.Supplier_ID = T3.Supplier_ID
AND DATEADD('D', 1, T3.[Date]) = T4.[Date]
);
CREATE VIEW TableA_Periods (Supplier_ID, start_date, end_date)
AS
SELECT DISTINCT T5.Supplier_ID,
(
SELECT MAX(S1.start_date)
FROM TableA_StartDates AS S1
WHERE S1.Supplier_ID = T5.Supplier_ID
AND S1.start_date <= T5.[Date]
),
(
SELECT MIN(E1.end_date)
FROM TableA_EndDates AS E1
WHERE E1.Supplier_ID = T5.Supplier_ID
AND T5.[Date] <= E1.end_date
)
FROM TableA AS T5;
SELECT P1.Supplier_ID, P1.start_date, P1.end_date,
DATEDIFF('D', P1.start_date, P1.end_date) + 1 AS Days
FROM TableA_Periods AS P1;
You have a lot of business rules with some unique assumptions. Eg TableA is never empty, TableB is always empty before you run this
Regardless, the code below will work using your sample data:
Dim rs As Recordset
Dim dbs As Database, qdf As QueryDef, strSQL As String
Set dbs = CurrentDb
Dim Supplier_ID As Integer
Dim Days As Integer
Dim FirstDate As Date
Set qdf = dbs.CreateQueryDef("", "select [Date], Supplier_ID from tableA order by [date] ")
Set rs = qdf.OpenRecordset()
Supplier_ID = rs!Supplier_ID
FirstDate = rs!Date
While Not rs.EOF
If rs!Supplier_ID <> Supplier_ID Then
If Supplier_ID <> 0 Then
' we don't want to insert the first time we run through this, so we check if Supplier_ID is not zero
dbs.Execute ("insert into tableB ([Date], Supplier_ID, Days) select #" + Format(FirstDate, "dd-mmm-yyyy") + "#, " + Str(Supplier_ID) + ", " + Str(Days))
Supplier_ID = rs!Supplier_ID
FirstDate = rs!Date
Days = 0
End If
End If
Days = Days + 1
rs.MoveNext
Wend
dbs.Execute ("insert into tableB ([Date], Supplier_ID, Days) select #" + Format(FirstDate, "dd-mmm-yyyy") + "#, " + Str(Supplier_ID) + ", " + Str(Days))
While you can do it, Access (and generally SQL) isn't the best for doing row by row comparisons. Even though you can use cursors or code like the example above, maintenance can be a challenge!
I don't think this can be done in a single SQL, so you'll have to write some code. My first idea would be to make some kind of dictionary (Key = SupplierID, Value = (FirstDate, LastDate)) and use an algorithm that iterates through the data in Table A and fills the dictionary, kind of like this (pseudo-code):
records = recordset: SELECT * FROM Table A ORDER BY Date
Do Until records.EOF
If dictionary contains records!SupplierID
If dictionaryEntry.LastDate = records!Date - 1
dictionaryEntry.LastDate = records!Date
Else
Make Table B Entry (Days = LastDate - FirstDate) and remove dictionary entry
End If
Else
Create dictionary entry for this Supplier with LastDate = FirstDate = records!Date
End If
records.MoveNext
Loop
records.Close
Make Table B Entries for all remaining entries in the dictionary
For the dictionary, you could use a Scripting.Dictionary with the value being a 2-Element-Array.