所有结果的简单SQL查询

时间:2015-08-20 10:06:33

标签: sql

<?php
if(!empty($error)) {
?>
   <h4 class="bg-danger"><?php echo $error; ?></h4>
<?php
}
?>

,结果应为:

CREATE TABLE [dbo].[tbl_Travel]
(
    [TE_ID] [int] IDENTITY(1,1) NOT NULL,
    [TRAVEL_TYPE] [varchar](12) NULL,
    [TRAVEL_MODE] [varchar](35) NULL,
    [TRAVEL_CLASS] [nchar](10) NULL)

SET PRIMARY KEY TO TE_ID

INSERT INTO [TAMSMVC].[dbo].[tbl_Travel] VALUES  ('Return', 'Airlines', 'Economy')
INSERT INTO [TAMSMVC].[dbo].[tbl_Travel] VALUES  ('Single', 'Airlines', 'Business')
INSERT INTO [TAMSMVC].[dbo].[tbl_Travel] VALUES  ('Return', 'Airlines', 'Business')
INSERT INTO [TAMSMVC].[dbo].[tbl_Travel] VALUES  ('Single', 'Railway', 'Second')
INSERT INTO [TAMSMVC].[dbo].[tbl_Travel] VALUES  ('Return', 'Railway', 'First')
INSERT INTO [TAMSMVC].[dbo].[tbl_Travel] VALUES  ('Return', 'Airlines', 'Business')
INSERT INTO [TAMSMVC].[dbo].[tbl_Travel] VALUES  ('Return', 'Airlines', 'Economy')

CREATE TABLE [dbo].[tbl_Journey]
(
    [JOURNET_ID] [int] IDENTITY(1,1) NOT NULL,
    [TE_ID] [int] NULL,
    [JOURNEY_FROM] [varchar](30) NULL,
    [JOURNEY_TO] [varchar](30) NULL)

SET PRIMARY KEY TO [JOURNET_ID]

INSERT INTO [TAMSMVC].[dbo].[tbl_Journey] VALUES (1,'Mumbai','PUNE')
INSERT INTO [TAMSMVC].[dbo].[tbl_Journey] VALUES (1,'PUNE','Mumbai')
INSERT INTO [TAMSMVC].[dbo].[tbl_Journey] VALUES (2,'BANGALORE','GOA')
INSERT INTO [TAMSMVC].[dbo].[tbl_Journey] VALUES (3,'CHENNAI','PANAJI')
INSERT INTO [TAMSMVC].[dbo].[tbl_Journey] VALUES (3,'PANAJI','CHENNAI')
INSERT INTO [TAMSMVC].[dbo].[tbl_Journey] VALUES (4,'DELHI','KOLKATA')
INSERT INTO [TAMSMVC].[dbo].[tbl_Journey] VALUES (5,'BHOPAL','SHIMALA')
INSERT INTO [TAMSMVC].[dbo].[tbl_Journey] VALUES (5,'SHIMALA','BHOPAL')

结果我想要Journey_ID TE_ID Journey_From Journey_To TRAVEL_TYPE [TRAVEL_MODE TRAVEL_CLASS CountofTEID 1 1 Mumbai PUNE Return Airlines Economy 2 3 2 BANGALORE GOA Single Airlines Business 1 4 3 CHENNAI PANAJI Return Airlines Business 2 6 4 DELHI KOLKATA Single Railway Second 1 7 5 BHOPAL SHIMALA Return Railway First 2 null 6 null null Return Airlines Economy 0 null 7 null null Return Airlines Business 0 表中的所有行,所有行程的计数和最小Travel的单个记录

1 个答案:

答案 0 :(得分:0)

这是我刚试过的东西:

SELECT ROW_NUMBER() OVER(PARTITION BY A.TE_ID ORDER BY A.TE_ID) AS ROWNO, JOURNET_ID, A.TE_ID, JOURNEY_FROM, JOURNEY_TO, TRAVEL_TYPE, TRAVEL_MODE, TRAVEL_CLASS
INTO #FINALTEMPDATA
FROM #TEMPA A 
OUTER APPLY (
    SELECT * FROM #TEMPJ J WHERE A.TE_ID = J.TE_ID
) APP

SELECT JOURNET_ID, FA.TE_ID, JOURNEY_FROM, JOURNEY_TO, TRAVEL_TYPE, TRAVEL_MODE, TRAVEL_CLASS, COUNTOFID
FROM #FINALTEMPDATA FA
INNER JOIN (
    SELECT FB.TE_ID, COUNT(*) AS COUNTOFID FROM #FINALTEMPDATA FB
    GROUP BY FB.TE_ID
) FC ON FA.TE_ID = FC.TE_ID
WHERE FA.ROWNO = 1